{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第1章 项目体系架构设计\n",
    "\n",
    "## 1.1 项目系统架构\n",
    "\n",
    "项目以推荐系统建设领域知名的经过修改过的中文亚马逊电商数据集作为依托，以某电商网站真实业务数据架构为基础，构建了符合教学体系的一体化的电商推荐系统，包含了离线推荐与实时推荐体系，综合利用了协同过滤算法以及基于内容的推荐方法来提供混合推荐。提供了从前端应用、后台服务、算法设计实现、平台部署等多方位的闭环的业务实现。\n",
    "\n",
    "电商推荐系统架构图\n",
    "\n",
    "![](images/架构图.png)\n",
    "\n",
    "架构图代码，使用mermaid渲染出架构图\n",
    "\n",
    "```\n",
    "graph TD\n",
    "A[前端可视化, Angular] --> B[后端业务逻辑, Spring]\n",
    "B --> C[业务数据库]\n",
    "C --> D[持久化: MongoDB]\n",
    "C --> E[缓存: Redis]\n",
    "D --> F[离线推荐服务, Spark MLlib]\n",
    "D --> G[离线统计服务, Spark SQL]\n",
    "B --> H[日志采集服务, Flume]\n",
    "H --> I[消息队列, Kafka]\n",
    "I --> J[实时推荐, Spark Streaming]\n",
    "E --> J\n",
    "```\n",
    "\n",
    "- 用户可视化：主要负责实现和用户的交互以及业务数据的展示，主体采用AngularJS2进行实现，部署在Apache服务上。\n",
    "- 综合业务服务：主要实现JavaEE层面整体的业务逻辑，通过Spring进行构建，对接业务需求。部署在Tomcat上。\n",
    "\n",
    "### 【数据存储部分】\n",
    "\n",
    "- 业务数据库：项目采用广泛应用的文档数据库MongoDB作为主数据库，主要负责平台业务逻辑数据的存储。\n",
    "- 缓存数据库：项目采用Redis作为缓存数据库，主要用来支撑实时推荐系统部分对于数据的高速获取需求。\n",
    "\n",
    "#### 【离线推荐部分】\n",
    "\n",
    "- 离线统计服务：批处理统计性业务采用Spark Core + Spark SQL进行实现，实现对指标类数据的统计任务。\n",
    "- 离线推荐服务：离线推荐业务采用Spark Core + Spark MLlib进行实现，采用ALS算法进行实现。\n",
    "- 基于内容的推荐：采用TF-IDF算法提取UGC标签的关键词，计算商品之间的余弦相似度。\n",
    "- 基于物品的协同过滤推荐：实现传统的Item-CF算法。\n",
    "\n",
    "#### 【实时推荐部分】\n",
    "\n",
    "- 日志采集服务：通过利用Flume-ng对业务平台中用户对于电影的一次评分行为进行采集，实时发送到Kafka集群。\n",
    "- 消息缓冲服务：项目采用Kafka作为流式数据的缓存组件，接受来自Flume的数据采集请求。并将数据推送到项目的实时推荐系统部分。\n",
    "- 实时推荐服务：项目采用Spark Streaming作为实时推荐系统，通过接收Kafka中缓存的数据，通过设计的推荐算法实现对实时推荐的数据处理，并将结构合并更新到MongoDB数据库。\n",
    "\n",
    "## 1.2 项目数据流程\n",
    "\n",
    "电商推荐系统数据流图\n",
    "\n",
    "**略**\n",
    "\n",
    "### 【系统初始化部分】\n",
    "0.\t通过Spark SQL将系统初始化数据加载到MongoDB中。\n",
    "【离线推荐部分】\n",
    "1.\t离线统计服务从MongoDB中加载数据，将【商品平均评分统计】、【商品评分个数统计】、【最近商品评分个数统计】三个统计算法进行运行实现，并将计算结果回写到MongoDB中；离线推荐服务从MongoDB中加载数据，通过ALS算法分别将【用户推荐结果矩阵】、【商品相似度矩阵】回写到MongoDB中。\n",
    "### 【实时推荐部分】\n",
    "2.\tFlume从综合业务服务的运行日志中读取日志更新，并将更新的日志实时推送到Kafka中；Kafka在收到这些日志之后，通过kafkaStream程序对获取的日志信息进行过滤处理，获取用户评分数据流【userId|productId|score|timestamp】，并发送到另外一个Kafka队列；Spark Streaming监听Kafka队列，实时获取Kafka过滤出来的用户评分数据流，融合存储在Redis中的用户最近评分队列数据，提交给实时推荐算法，完成对用户新的推荐结果计算；计算完成之后，将新的推荐结构和MongDB数据库中的推荐结果进行合并。\n",
    "### 【业务系统部分】\n",
    "3.\t推荐结果展示部分，从MongoDB中将离线推荐结果、实时推荐结果、内容推荐结果进行混合，综合给出相对应的数据。\n",
    "4.\t商品信息查询服务通过对接MongoDB实现对商品信息的查询操作。\n",
    "5.\t商品评分部分，获取用户通过UI给出的评分动作，后台服务进行数据库记录后，一方面将数据推动到Redis群中，另一方面，通过预设的日志框架输出到Tomcat中的日志中。\n",
    "6.\t商品标签部分，项目提供用户对电影打标签服务。\n",
    "\n",
    "## 1.3 数据模型\n",
    "\n",
    "1. 商品数据表\n",
    "\n",
    "| 字段名 | 字段类型 | 字段描述 | 字段备注 |\n",
    "|-------|---------|---------|--------|\n",
    "|productId|Int|商品ID|\n",
    "|name|String|商品名字|\n",
    "|categories|String|商品分类|\n",
    "|imageUrl|String|图片url|\n",
    "|tags|String|UGC标签|\n",
    "\n",
    "2. 评分数据表\n",
    "\n",
    "字段名|字段类型|字段描述|字段备注\n",
    "-----|------|-------|------\n",
    "userid|Int|用户ID|\t\n",
    "productId|Int|商品ID|\t\n",
    "score|Double|商品分值|\n",
    "timestamp|Long|评分时间|\t\n",
    "\n",
    "3. 用户表\n",
    "\n",
    "字段名|字段类型|字段描述|字段备注\n",
    "-----|-------|-------|-----\n",
    "productId|Int|用户的ID\n",
    "username|String|用户名\n",
    "password|String|用户密码\n",
    "first|boolean|用于是否第一次登录\n",
    "timestamp|Long|用户创建的时间\n",
    "\n",
    "# 第2章 工具环境搭建\n",
    "\n",
    "我们的项目中用到了多种工具进行数据的存储、计算、采集和传输，本章主要简单介绍设计的工具环境搭建。\n",
    "\n",
    "如果机器的配置不足，推荐只采用一台虚拟机进行配置，而非完全分布式，将该虚拟机CPU的内存设置的尽可能大，推荐为CPU > 4、MEM > 4GB。\n",
    "\n",
    "## 2.1 MongoDB（单节点）环境配置\n",
    "\n",
    "```sh\n",
    "// 通过WGET下载Linux版本的MongoDB\n",
    "[bigdata@linux ~]$ wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-3.4.3.tgz\n",
    "// 将压缩包解压到指定目录\n",
    "[bigdata@linux backup]$ tar -xf mongodb-linux-x86_64-rhel62-3.4.3.tgz -C ~/\n",
    "// 将解压后的文件移动到最终的安装目录\n",
    "[bigdata@linux ~]$ mv mongodb-linux-x86_64-rhel62-3.4.3/ /usr/local/mongodb\n",
    "// 在安装目录下创建data文件夹用于存放数据和日志\n",
    "[bigdata@linux mongodb]$ mkdir /usr/local/mongodb/data/\n",
    "// 在data文件夹下创建db文件夹，用于存放数据\n",
    "[bigdata@linux mongodb]$ mkdir /usr/local/mongodb/data/db/\n",
    "// 在data文件夹下创建logs文件夹，用于存放日志\n",
    "[bigdata@linux mongodb]$ mkdir /usr/local/mongodb/data/logs/\n",
    "// 在logs文件夹下创建log文件\n",
    "[bigdata@linux mongodb]$ touch /usr/local/mongodb/data/logs/ mongodb.log\n",
    "\n",
    "// 在data文件夹下创建mongodb.conf配置文件\n",
    "[bigdata@linux mongodb]$ touch /usr/local/mongodb/data/mongodb.conf\n",
    "// 在mongodb.conf文件中输入如下内容\n",
    "[bigdata@linux mongodb]$ vim ./data/mongodb.conf\n",
    "```\n",
    "\n",
    "配置文件内容：\n",
    "\n",
    "```\n",
    "#端口号port = 27017\n",
    "#数据目录\n",
    "dbpath = /usr/local/mongodb/data/db\n",
    "#日志目录\n",
    "logpath = /usr/local/mongodb/data/logs/mongodb.log\n",
    "#设置后台运行\n",
    "fork = true\n",
    "#日志输出方式\n",
    "logappend = true\n",
    "```\n",
    "\n",
    "完成MongoDB的安装后，启动MongoDB服务器：\n",
    "\n",
    "```sh\n",
    "// 启动MongoDB服务器\n",
    "[bigdata@linux mongodb]$ sudo /usr/local/mongodb/bin/mongod -config /usr/local/mongodb/data/mongodb.conf\n",
    "// 访问MongoDB服务器\n",
    "[bigdata@linux mongodb]$ /usr/local/mongodb/bin/mongo\n",
    "// 停止MongoDB服务器\n",
    "[bigdata@linux mongodb]$ sudo /usr/local/mongodb/bin/mongod -shutdown -config /usr/local/mongodb/data/mongodb.conf\n",
    "```\n",
    "\n",
    "## 2.2 Redis（单节点）环境配置\n",
    "\n",
    "```sh\n",
    "// 通过WGET下载REDIS的源码\n",
    "[bigdata@linux ~]$wget http://download.redis.io/releases/redis-4.0.2.tar.gz \n",
    "// 将源代码解压到安装目录\n",
    "[bigdata@linux ~]$ tar -xf redis-4.0.2.tar.gz -C ~/\n",
    "// 进入Redis源代码目录，编译安装\n",
    "[bigdata@linux ~]$ cd redis-4.0.2/\n",
    "// 安装GCC\n",
    "[bigdata@linux ~]$ sudo yum install gcc\n",
    "// 编译源代码\n",
    "[bigdata@linux redis-4.0.2]$ make MALLOC=libc\n",
    "// 编译安装\n",
    "[bigdata@linux redis-4.0.2]$ sudo make install\n",
    "// 创建配置文件\n",
    "[bigdata@linux redis-4.0.2]$ sudo cp ~/redis-4.0.2/redis.conf /etc/ \n",
    "// 修改配置文件中以下内容\n",
    "[bigdata@linux redis-4.0.2]$ sudo vim /etc/redis.conf\n",
    "daemonize yes   #37行  #是否以后台daemon方式运行，默认不是后台运行\n",
    "pidfile /var/run/redis/redis.pid   #41行  #redis的PID文件路径（可选）\n",
    "bind 0.0.0.0    #64行  #绑定主机IP，默认值为127.0.0.1，我们是跨机器运行，所以需要更改\n",
    "logfile /var/log/redis/redis.log   #104行  #定义log文件位置，模式log信息定向到stdout，输出到/dev/null（可选）\n",
    "dir “/usr/local/rdbfile”  #188行  #本地数据库存放路径，默认为./，编译安装默认存在在/usr/local/bin下（可选）\n",
    "在安装完Redis之后，启动Redis\n",
    "// 启动Redis服务器\n",
    "[bigdata@linux redis-4.0.2]$ redis-server /etc/redis.conf\n",
    "// 连接Redis服务器\n",
    "[bigdata@linux redis-4.0.2]$ redis-cli\n",
    "// 停止Redis服务器\n",
    "[bigdata@linux redis-4.0.2]$ redis-cli shutdown\n",
    "```\n",
    "\n",
    "在安装完Redis之后，启动Redis\n",
    "\n",
    "```sh\n",
    "// 启动Redis服务器\n",
    "[bigdata@linux redis-4.0.2]$ redis-server /etc/redis.conf\n",
    "// 连接Redis服务器\n",
    "[bigdata@linux redis-4.0.2]$ redis-cli\n",
    "// 停止Redis服务器\n",
    "[bigdata@linux redis-4.0.2]$ redis-cli shutdown\n",
    "```\n",
    "\n",
    "## 2.3 Spark（单节点）环境配置\n",
    "\n",
    "```sh\n",
    "// 通过wget下载zookeeper安装包\n",
    "[bigdata@linux ~]$ wget https://d3kbcqa49mib13.cloudfront.net/spark-2.1.1-bin-hadoop2.7.tgz \n",
    "// 将spark解压到安装目录\n",
    "[bigdata@linux ~]$ tar –xf spark-2.1.1-bin-hadoop2.7.tgz –C ./cluster\n",
    "// 进入spark安装目录\n",
    "[bigdata@linux cluster]$ cd spark-2.1.1-bin-hadoop2.7/\n",
    "// 复制slave配置文件\n",
    "[bigdata@linux spark-2.1.1-bin-hadoop2.7]$ cp ./conf/slaves.template ./conf/slaves    \n",
    "// 修改slave配置文件\n",
    "[bigdata@linux spark-2.1.1-bin-hadoop2.7]$ vim ./conf/slaves\n",
    "linux  #在文件最后将本机主机名进行添加\n",
    "// 复制Spark-Env配置文件\n",
    "[bigdata@linux spark-2.1.1-bin-hadoop2.7]$ cp ./conf/spark-env.sh.template ./conf/spark-env.sh \n",
    "SPARK_MASTER_HOST=linux       #添加spark master的主机名\n",
    "SPARK_MASTER_PORT=7077        #添加spark master的端口号\n",
    "```\n",
    "\n",
    "安装完成之后，启动Spark\n",
    "\n",
    "```sh\n",
    "// 启动Spark集群\n",
    "[bigdata@linux spark-2.1.1-bin-hadoop2.7]$ sbin/start-all.sh\n",
    "// 访问Spark集群，浏览器访问http://linux:8080\n",
    " \n",
    "// 关闭Spark集群\n",
    "[bigdata@linux spark-2.1.1-bin-hadoop2.7]$ sbin/stop-all.sh\n",
    "```\n",
    "\n",
    "## 2.4 Zookeeper（单节点）环境配置\n",
    "\n",
    "```sh\n",
    "// 通过wget下载zookeeper安装包\n",
    "[bigdata@linux ~]$ wget http://mirror.bit.edu.cn/apache/zookeeper/zookeeper-3.4.10/zookeeper-3.4.10.tar.gz \n",
    "// 将zookeeper解压到安装目录\n",
    "[bigdata@linux ~]$ tar –xf zookeeper-3.4.10.tar.gz –C ./cluster\n",
    "// 进入zookeeper安装目录\n",
    "[bigdata@linux cluster]$ cd zookeeper-3.4.10/\n",
    "// 创建data数据目录\n",
    "[bigdata@linux zookeeper-3.4.10]$ mkdir data/\n",
    "// 复制zookeeper配置文件\n",
    "[bigdata@linux zookeeper-3.4.10]$ cp ./conf/zoo_sample.cfg ./conf/zoo.cfg   \n",
    "// 修改zookeeper配置文件\n",
    "[bigdata@linux zookeeper-3.4.10]$ vim conf/zoo.cfg\n",
    "dataDir=/home/bigdata/cluster/zookeeper-3.4.10/data  #将数据目录地址修改为创建的目录\n",
    "// 启动Zookeeper服务\n",
    "[bigdata@linux zookeeper-3.4.10]$ bin/zkServer.sh start\n",
    "// 查看Zookeeper服务状态\n",
    "[bigdata@linux zookeeper-3.4.10]$ bin/zkServer.sh status\n",
    "ZooKeeper JMX enabled by default\n",
    "Using config: /home/bigdata/cluster/zookeeper-3.4.10/bin/../conf/zoo.cfg\n",
    "Mode: standalone\n",
    "// 关闭Zookeeper服务\n",
    "[bigdata@linux zookeeper-3.4.10]$ bin/zkServer.sh stop\n",
    "```\n",
    "\n",
    "## 2.5 Flume-ng（单节点）环境配置\n",
    "\n",
    "```sh\n",
    "// 通过wget下载zookeeper安装包\n",
    "[bigdata@linux ~]$ wget http://www.apache.org/dyn/closer.lua/flume/1.8.0/apache-flume-1.8.0-bin.tar.gz\n",
    "// 将zookeeper解压到安装目录\n",
    "[bigdata@linux ~]$ tar –xf apache-flume-1.8.0-bin.tar.gz –C ./cluster\n",
    "// 等待项目部署时使用\n",
    "```\n",
    "\n",
    "## 2.6 Kafka（单节点）环境配置\n",
    "\n",
    "```sh\n",
    "// 通过wget下载zookeeper安装包\n",
    "[bigdata@linux ~]$ wget http://mirrors.tuna.tsinghua.edu.cn/apache/kafka/0.10.2.1/kafka_2.11-0.10.2.1.tgz \n",
    "// 将kafka解压到安装目录\n",
    "[bigdata@linux ~]$ tar –xf kafka_2.12-0.10.2.1.tgz –C ./cluster\n",
    "// 进入kafka安装目录\n",
    "[bigdata@linux cluster]$ cd kafka_2.12-0.10.2.1/   \n",
    "// 修改kafka配置文件\n",
    "[bigdata@linux kafka_2.12-0.10.2.1]$ vim config/server.properties\n",
    "host.name=linux                  #修改主机名\n",
    "port=9092                         #修改服务端口号\n",
    "zookeeper.connect=linux:2181     #修改Zookeeper服务器地址\n",
    "// 启动kafka服务 !!! 启动之前需要启动Zookeeper服务\n",
    "[bigdata@linux kafka_2.12-0.10.2.1]$ bin/kafka-server-start.sh -daemon ./config/server.properties\n",
    "// 关闭kafka服务\n",
    "[bigdata@linux kafka_2.12-0.10.2.1]$ bin/kafka-server-stop.sh\n",
    "// 创建topic\n",
    "[bigdata@linux kafka_2.12-0.10.2.1]$ bin/kafka-topics.sh --create --zookeeper linux:2181 --replication-factor 1 --partitions 1 --topic recommender\n",
    "// kafka-console-producer\n",
    "[bigdata@linux kafka_2.12-0.10.2.1]$ bin/kafka-console-producer.sh --broker-list linux:9092 --topic recommender\n",
    "// kafka-console-consumer\n",
    "[bigdata@linux kafka_2.12-0.10.2.1]$ bin/kafka-console-consumer.sh --bootstrap-server linux:9092 --topic recommender\n",
    "```\n",
    "\n",
    "# 第3章 创建项目并初始化业务数据\n",
    "\n",
    "我们的项目主体用Scala编写，采用IDEA作为开发环境进行项目编写，采用maven作为项目构建和管理工具。\n",
    "\n",
    "## 3.1 在IDEA中创建maven项目\n",
    "\n",
    "打开IDEA，创建一个maven项目，命名为ECommerceRecommendSystem。为了方便后期的联调，我们会把业务系统的代码也添加进来，所以我们可以以ECommerceRecommendSystem作为父项目，并在其下建一个名为recommender的子项目，然后再在下面搭建多个子项目用于提供不同的推荐服务。\n",
    "\n",
    "## 3.1.1 项目框架搭建\n",
    "\n",
    "在ECommerceRecommendSystem的pom.xml文件中加入元素`<packaging>pom</packaging>`，然后新建一个maven module作为子项目，命名为recommender。同样的，再以recommender为父项目，在它的pom.xml中加入`<packing>pom</packaging>`，然后新建一个maven module作为子项目。我们的第一步是初始化业务数据，所以子项目命名为DataLoader。\n",
    "\n",
    "父项目只是为了规范化项目结构，方便依赖管理，本身是不需要代码实现的，所以ECommerceRecommendSystem和recommender下的src文件夹都可以删掉。\n",
    "\n",
    "目前的整体项目框架如下：\n",
    "\n",
    "**略**\n",
    "\n",
    "## 3.1.2 声明项目中工具的版本信息\n",
    "\n",
    "我们整个项目需要用到多个工具，它们的不同版本可能会对程序运行造成影响，所以应该在最外层的ECommerceRecommendSystem中声明所有子项目共用的版本信息。\n",
    "在pom.xml中加入以下配置：\n",
    "\n",
    "`ECommerceRecommendSystem/pom.xml`\n",
    "\n",
    "```xml\n",
    "    <properties>\n",
    "        <mysql.version>6.0.5</mysql.version>\n",
    "        <shiro.version>1.3.2</shiro.version>\n",
    "        <spring.version>4.3.6.RELEASE</spring.version>\n",
    "        <spring.data.jpa.version>1.11.0.RELEASE</spring.data.jpa.version>\n",
    "        <log4j.version>1.2.17</log4j.version>\n",
    "        <quartz.version>2.2.3</quartz.version>\n",
    "        <slf4j.version>1.7.22</slf4j.version>\n",
    "        <hibernate.version>5.2.6.Final</hibernate.version>\n",
    "        <camel.version>2.18.2</camel.version>\n",
    "        <freemarker.version>2.3.23</freemarker.version>\n",
    "        <config.version>1.10</config.version>\n",
    "        <jackson.version>2.8.6</jackson.version>\n",
    "        <servlet.version>3.0.1</servlet.version>\n",
    "        <net.sf.json.version>2.4</net.sf.json.version>\n",
    "        <activemq.version>5.14.3</activemq.version>\n",
    "        <spark.version>2.1.1</spark.version>\n",
    "        <scala.version>2.11.8</scala.version>\n",
    "        <hadoop.version>2.7.3</hadoop.version>\n",
    "        <mongodb-spark.version>2.0.0</mongodb-spark.version>\n",
    "        <casbah.version>3.1.1</casbah.version>\n",
    "        <elasticsearch-spark.version>5.6.2</elasticsearch-spark.version>\n",
    "        <elasticsearch.version>5.6.2</elasticsearch.version>\n",
    "        <jblas.version>1.2.1</jblas.version>\n",
    "    </properties>\n",
    "```\n",
    "\n",
    "### 3.1.3 添加项目依赖\n",
    "\n",
    "首先，对于整个项目而言，应该有同样的日志管理，我们在ECommerceRecommendSystem中引入公有依赖：\n",
    "\n",
    "```xml\n",
    "    <dependencies>\n",
    "        <!-- Logging -->\n",
    "        <dependency>\n",
    "            <groupId>org.slf4j</groupId>\n",
    "            <artifactId>jcl-over-slf4j</artifactId>\n",
    "            <version>${slf4j.version}</version>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.slf4j</groupId>\n",
    "            <artifactId>slf4j-api</artifactId>\n",
    "            <version>${slf4j.version}</version>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.slf4j</groupId>\n",
    "            <artifactId>slf4j-log4j12</artifactId>\n",
    "            <version>${slf4j.version}</version>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>log4j</groupId>\n",
    "            <artifactId>log4j</artifactId>\n",
    "            <version>${log4j.version}</version>\n",
    "        </dependency>\n",
    "        <!-- Logging End -->\n",
    "    </dependencies>\n",
    "```\n",
    "\n",
    "同样，对于maven项目的构建，可以引入公有的插件：\n",
    "\n",
    "```xml\n",
    "    <build>\n",
    "        <plugins>\n",
    "            <plugin>\n",
    "                <groupId>org.apache.maven.plugins</groupId>\n",
    "                <artifactId>maven-compiler-plugin</artifactId>\n",
    "                <version>3.6.1</version>\n",
    "                <configuration>\n",
    "                    <source>1.8</source>\n",
    "                    <target>1.8</target>\n",
    "                </configuration>\n",
    "            </plugin>\n",
    "        </plugins>\n",
    "        <pluginManagement>\n",
    "            <plugins>\n",
    "                <plugin>\n",
    "                    <groupId>org.apache.maven.plugins</groupId>\n",
    "                    <artifactId>maven-assembly-plugin</artifactId>\n",
    "                    <version>3.0.0</version>\n",
    "                    <executions>\n",
    "                        <execution>\n",
    "                            <id>make-assembly</id>\n",
    "                            <phase>package</phase>\n",
    "                            <goals>\n",
    "                                <goal>single</goal>\n",
    "                            </goals>\n",
    "                        </execution>\n",
    "                    </executions>\n",
    "                </plugin>\n",
    "                <plugin>\n",
    "                    <groupId>net.alchim31.maven</groupId>\n",
    "                    <artifactId>scala-maven-plugin</artifactId>\n",
    "                    <version>3.2.2</version>\n",
    "                    <executions>\n",
    "                        <execution>\n",
    "                            <goals>\n",
    "                                <goal>compile</goal>\n",
    "                                <goal>testCompile</goal>\n",
    "                            </goals>\n",
    "                        </execution>\n",
    "                    </executions>\n",
    "                </plugin>\n",
    "            </plugins>\n",
    "        </pluginManagement>\n",
    "    </build>\n",
    "```\n",
    "\n",
    "然后，在recommender模块中，我们可以为所有的推荐模块声明spark相关依赖（这里的dependencyManagement表示仅声明相关信息，子项目如果依赖需要自行引入）：\n",
    "\n",
    "`ECommerceRecommendSystem/recommender/pom.xml`\n",
    "\n",
    "```xml\n",
    "    <dependencyManagement>\n",
    "        <dependencies>\n",
    "\n",
    "            <!-- 引入Spark相关的Jar包 -->\n",
    "            <dependency>\n",
    "                <groupId>org.apache.spark</groupId>\n",
    "                <artifactId>spark-core_2.11</artifactId>\n",
    "                <version>2.1.1</version>\n",
    "                <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "                <!--<scope>provided</scope>-->\n",
    "            </dependency>\n",
    "            <dependency>\n",
    "                <groupId>org.apache.spark</groupId>\n",
    "                <artifactId>spark-sql_2.11</artifactId>\n",
    "                <version>2.1.1</version>\n",
    "                <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "                <!--<scope>provided</scope>-->\n",
    "            </dependency>\n",
    "            <dependency>\n",
    "                <groupId>org.apache.spark</groupId>\n",
    "                <artifactId>spark-streaming_2.11</artifactId>\n",
    "                <version>2.1.1</version>\n",
    "                <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "                <!--<scope>provided</scope>-->\n",
    "            </dependency>\n",
    "            <dependency>\n",
    "                <groupId>org.apache.spark</groupId>\n",
    "                <artifactId>spark-mllib_2.11</artifactId>\n",
    "                <version>2.1.1</version>\n",
    "                <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "                <!--<scope>provided</scope>-->\n",
    "            </dependency>\n",
    "            <dependency>\n",
    "                <groupId>org.apache.spark</groupId>\n",
    "                <artifactId>spark-graphx_2.11</artifactId>\n",
    "                <version>2.1.1</version>\n",
    "                <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "                <!--<scope>provided</scope>-->\n",
    "            </dependency>\n",
    "\n",
    "            <!-- 加入MongoDB的驱动 -->\n",
    "            <!-- 用于代码方式连接MongoDB -->\n",
    "            <dependency>\n",
    "                <groupId>org.mongodb</groupId>\n",
    "                <artifactId>casbah-core_2.11</artifactId>\n",
    "                <version>${casbah.version}</version>\n",
    "            </dependency>\n",
    "            <!-- 用于Spark和MongoDB的对接 -->\n",
    "            <dependency>\n",
    "                <groupId>org.mongodb.spark</groupId>\n",
    "                <artifactId>mongo-spark-connector_2.11</artifactId>\n",
    "                <version>${mongodb-spark.version}</version>\n",
    "            </dependency>\n",
    "\n",
    "            <!-- 引入Scala -->\n",
    "            <dependency>\n",
    "                <groupId>org.scala-lang</groupId>\n",
    "                <artifactId>scala-library</artifactId>\n",
    "                <version>${scala.version}</version>\n",
    "            </dependency>\n",
    "\n",
    "            <dependency>\n",
    "                <groupId>org.scalanlp</groupId>\n",
    "                <artifactId>jblas</artifactId>\n",
    "                <version>${jblas.version}</version>\n",
    "            </dependency>\n",
    "\n",
    "        </dependencies>\n",
    "    </dependencyManagement>\n",
    "```\n",
    "\n",
    "由于各推荐模块都是scala代码，还应该引入scala-maven-plugin插件，用于scala程序的编译。因为插件已经在父项目中声明，所以这里不需要再声明版本和具体配置：\n",
    "\n",
    "```xml\n",
    "    <build>\n",
    "        <plugins>\n",
    "            <!-- 如果父项目有声明plugin，那么子项目在引入的时候，不用声明版本和父项目已经声明的配置 -->\n",
    "            <plugin>\n",
    "                <groupId>net.alchim31.maven</groupId>\n",
    "                <artifactId>scala-maven-plugin</artifactId>\n",
    "            </plugin>\n",
    "        </plugins>\n",
    "    </build>\n",
    "```\n",
    "\n",
    "对于具体的DataLoader子项目，需要spark相关组件，还需要mongodb的相关依赖，我们在pom.xml文件中引入所有依赖（在父项目中已声明的不需要再加详细信息）：\n",
    "\n",
    "`ECommerceRecommendSystem/recommender/DataLoader/pom.xml`\n",
    "\n",
    "```xml\n",
    "    <dependencies>\n",
    "        <!-- Spark的依赖引入 -->\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-core_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-sql_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <!-- 引入Scala -->\n",
    "        <dependency>\n",
    "            <groupId>org.scala-lang</groupId>\n",
    "            <artifactId>scala-library</artifactId>\n",
    "            <version>${scala.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "\n",
    "        <!-- 加入MongoDB的驱动 -->\n",
    "        <!-- 用于代码方式连接MongoDB -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb</groupId>\n",
    "            <artifactId>casbah-core_2.11</artifactId>\n",
    "            <version>${casbah.version}</version>\n",
    "        </dependency>\n",
    "        <!-- 用于Spark和MongoDB的对接 -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb.spark</groupId>\n",
    "            <artifactId>mongo-spark-connector_2.11</artifactId>\n",
    "            <version>${mongodb-spark.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <dependency>\n",
    "            <groupId>org.apache.logging.log4j</groupId>\n",
    "            <artifactId>log4j-core</artifactId>\n",
    "            <version>2.9.1</version>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.logging.log4j</groupId>\n",
    "            <artifactId>log4j-api</artifactId>\n",
    "            <version>2.9.1</version>\n",
    "        </dependency>\n",
    "    </dependencies>\n",
    "```\n",
    "\n",
    "## 3.2 数据加载准备\n",
    "\n",
    "在src/main/目录下，可以看到已有的默认源文件目录是java，我们可以将其改名为scala。将数据文件products.csv，ratings.csv复制到资源文件目录src/main/resources下，我们将从这里读取数据并加载到mongodb中。\n",
    "\n",
    "### 3.2.1 Products数据集\n",
    "\n",
    "数据格式：productId, name, categoryIds, amazonId, imageUrl, categories, tags\n",
    "\n",
    "例如：\n",
    "\n",
    "```\n",
    "3982^Fuhlen 富勒 M8眩光舞者时尚节能无线鼠标(草绿)(眩光.悦动.时尚炫舞鼠标 12个月免换电池 高精度光学寻迹引擎 超细微接收器10米传输距离)^1057,439,736^B009EJN4T2^https://images-cn-4.ssl-images-amazon.com/images/I/31QPvUDNavL._SY300_QL70_.jpg^外设产品|鼠标|电脑/办公^富勒|鼠标|电子产品|好用|外观漂亮\n",
    "```\n",
    "\n",
    "Product数据集有7个字段，每个字段之间通过“^”符号进行分割。我们用到的字段为：\n",
    "\n",
    "字段名|字段类型|字段描述|字段备注\n",
    "-----|-------|------|-------\n",
    "productId|Int|商品ID\t\n",
    "name|String|商品名称\t\n",
    "categories|String|商品分类\t\n",
    "imageUrl|String|商品图片\t\n",
    "tags|String|UGC标签\n",
    "\n",
    "### 3.1.2 Ratings数据集\n",
    "\n",
    "数据格式：\n",
    "userId,ProductId,rating,timestamp\n",
    "\n",
    "```\n",
    "e.g.\n",
    "1,31,2.5,1260759144\n",
    "```\n",
    "\n",
    "Rating数据集有4个字段, 每个字段之间通过“,”分割。\n",
    "\n",
    "字段名|字段类型|字段描述|字段备注\n",
    "-----|-------|------|-------\n",
    "userId|Int|用户ID\n",
    "productId|Int|商品ID\n",
    "score|Double|评分\n",
    "timestamp|Long|评分的时间\n",
    "\n",
    "### 3.1.4 日志管理配置文件\n",
    "\n",
    "log4j对日志的管理，需要通过配置文件来生效。在src/main/resources下新建配置文件log4j.properties，写入以下内容：\n",
    "\n",
    "```properties\n",
    "log4j.rootLogger=info, stdout\n",
    "log4j.appender.stdout=org.apache.log4j.ConsoleAppender\n",
    "log4j.appender.stdout.layout=org.apache.log4j.PatternLayout\n",
    "log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS}  %5p --- [%50t]  %-80c(line:%5L)  :  %m%n\n",
    "\n",
    "log4j.appender.R=org.apache.log4j.RollingFileAppender\n",
    "log4j.appender.R.File=../log/agent.log\n",
    "log4j.appender.R.MaxFileSize=1024KB\n",
    "log4j.appender.R.MaxBackupIndex=1\n",
    "\n",
    "log4j.appender.R.layout=org.apache.log4j.PatternLayout\n",
    "log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS}  %5p --- [%50t]  %-80c(line:%6L)  :  %m%n\n",
    "```\n",
    "\n",
    "## 3.2 数据初始化到MongoDB\n",
    "\n",
    "### 3.2.1 启动MongoDB数据库（略）\n",
    "\n",
    "### 3.2.2 数据加载程序主体实现\n",
    "\n",
    "我们会为原始数据定义几个样例类，通过SparkContext的textFile方法从文件中读取数据，并转换成DataFrame，再利用Spark SQL提供的write方法进行数据的分布式插入。\n",
    "\n",
    "在DataLoader/src/main/scala下新建package，命名为com.atguigu.dataloader，新建名为DataLoader的scala class文件。\n",
    "\n",
    "程序主体代码如下：\n",
    "\n",
    "```scala\n",
    "package com.atguigu.dataloader\n",
    "\n",
    "import com.mongodb.casbah.commons.MongoDBObject\n",
    "import com.mongodb.casbah.{MongoClient, MongoClientURI}\n",
    "import org.apache.spark.SparkConf\n",
    "import org.apache.spark.sql.{DataFrame, SparkSession}\n",
    "\n",
    "case class Product(productId: Int, name: String, categories: String, imageUrl: String, tags: String)\n",
    "\n",
    "case class Rating(userId: Int, productId: Int, score: Double, timestamp: Int)\n",
    "\n",
    "case class MongoConfig(uri: String, db: String)\n",
    "\n",
    "// 数据的主加载服务\n",
    "object DataLoader {\n",
    "\n",
    "  // products.csv和ratings.csv数据集的绝对路径\n",
    "  val PRODUCTS_DATA_PATH = \"/Users/yuanzuo/Desktop/ECommerceRecommender/recommender/DataLoader/src/main/resources/products.csv\"\n",
    "  val RATING_DATA_PATH = \"/Users/yuanzuo/Desktop/ECommerceRecommender/recommender/DataLoader/src/main/resources/ratings.csv\"\n",
    "\n",
    "  val MONGODB_PRODUCT_COLLECTION = \"Products\"\n",
    "  val MONGODB_RATING_COLLECTION = \"Rating\"\n",
    "\n",
    "  // 程序的入口\n",
    "  def main(args: Array[String]): Unit = {\n",
    "\n",
    "    val config = Map(\n",
    "      \"spark.cores\" -> \"local[*]\",\n",
    "      \"mongo.uri\" -> \"mongodb://localhost:27017/recommender\",\n",
    "      \"mongo.db\" -> \"recommender\"\n",
    "    )\n",
    "\n",
    "    val sparkConf = new SparkConf().setAppName(\"DataLoader\").setMaster(config.get(\"spark.cores\").get)\n",
    "\n",
    "    val spark = SparkSession.builder().config(sparkConf).getOrCreate()\n",
    "\n",
    "    spark.sparkContext.setLogLevel(\"ERROR\")\n",
    "\n",
    "    import spark.implicits._\n",
    "\n",
    "    val productRDD = spark.sparkContext.textFile(PRODUCTS_DATA_PATH)\n",
    "    val productDF = productRDD.map(item =>{\n",
    "      val attr = item.split(\"\\\\^\")\n",
    "      Product(attr(0).toInt, attr(1).trim, attr(5).trim, attr(4).trim, attr(6).trim)\n",
    "    }).toDF()\n",
    "\n",
    "    val ratingRDD = spark.sparkContext.textFile(RATING_DATA_PATH)\n",
    "    val ratingDF = ratingRDD.map(item => {\n",
    "      val attr = item.split(\",\")\n",
    "      Rating(attr(0).toInt,attr(1).toInt,attr(2).toDouble,attr(3).toInt)\n",
    "    }).toDF()\n",
    "\n",
    "    implicit val mongoConfig = MongoConfig(config.get(\"mongo.uri\").get,config.get(\"mongo.db\").get)\n",
    "\n",
    "    storeDataInMongoDB(productDF, ratingDF)\n",
    "\n",
    "    spark.stop()\n",
    "  }\n",
    "\n",
    "  // 将数据保存到MongoDB中的方法\n",
    "  def storeDataInMongoDB(productDF: DataFrame, ratingDF: DataFrame)(implicit mongoConfig: MongoConfig): Unit = {\n",
    "\n",
    "    //新建一个到MongoDB的连接\n",
    "    val mongoClient = MongoClient(MongoClientURI(mongoConfig.uri))\n",
    "\n",
    "    //如果MongoDB中有对应的数据库，那么应该删除\n",
    "    mongoClient(mongoConfig.db)(MONGODB_PRODUCT_COLLECTION).dropCollection()\n",
    "    mongoClient(mongoConfig.db)(MONGODB_RATING_COLLECTION).dropCollection()\n",
    "\n",
    "    //将当前数据写入到MongoDB\n",
    "    productDF\n",
    "      .write\n",
    "      .option(\"uri\",mongoConfig.uri)\n",
    "      .option(\"collection\", MONGODB_PRODUCT_COLLECTION)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "\n",
    "    ratingDF\n",
    "      .write\n",
    "      .option(\"uri\",mongoConfig.uri)\n",
    "      .option(\"collection\",MONGODB_RATING_COLLECTION)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "\n",
    "\n",
    "    //对数据表建索引\n",
    "    mongoClient(mongoConfig.db)(MONGODB_PRODUCT_COLLECTION).createIndex(MongoDBObject(\"productId\" -> 1))\n",
    "    mongoClient(mongoConfig.db)(MONGODB_RATING_COLLECTION).createIndex(MongoDBObject(\"userId\" -> 1))\n",
    "    mongoClient(mongoConfig.db)(MONGODB_RATING_COLLECTION).createIndex(MongoDBObject(\"productId\" -> 1))\n",
    "\n",
    "    //关闭MongoDB的连接\n",
    "    mongoClient.close()\n",
    "  }\n",
    "}\n",
    "```\n",
    "\n",
    "# 第4章 离线推荐服务建设\n",
    "\n",
    "## 4.1 离线推荐服务\n",
    "\n",
    "离线推荐服务是综合用户所有的历史数据，利用设定的离线统计算法和离线推荐算法周期性的进行结果统计与保存，计算的结果在一定时间周期内是固定不变的，变更的频率取决于算法调度的频率。\n",
    "\n",
    "离线推荐服务主要计算一些可以预先进行统计和计算的指标，为实时计算和前端业务相应提供数据支撑。\n",
    "\n",
    "离线推荐服务主要分为统计性算法、基于物品的协同过滤、基于ALS的协同过滤推荐算法、基于内容相似度的推荐。\n",
    "\n",
    "在recommender下新建子项目StatisticsRecommender，pom.xml文件中只需引入spark、scala和mongodb的相关依赖：\n",
    "\n",
    "```xml\n",
    "    <dependencies>\n",
    "        <!-- Spark的依赖引入 -->\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-core_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-sql_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <!-- 引入Scala -->\n",
    "        <dependency>\n",
    "            <groupId>org.scala-lang</groupId>\n",
    "            <artifactId>scala-library</artifactId>\n",
    "            <version>${scala.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <!-- 加入MongoDB的驱动 -->\n",
    "        <!-- 用于代码方式连接MongoDB -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb</groupId>\n",
    "            <artifactId>casbah-core_2.11</artifactId>\n",
    "            <version>${casbah.version}</version>\n",
    "        </dependency>\n",
    "        <!-- 用于Spark和MongoDB的对接 -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb.spark</groupId>\n",
    "            <artifactId>mongo-spark-connector_2.11</artifactId>\n",
    "            <version>${mongodb-spark.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "    </dependencies>\n",
    "```\n",
    "\n",
    "在resources文件夹下引入log4j.properties，然后在src/main/scala下新建scala单例对象com.atguigu.statistics.StatisticsRecommender。\n",
    "\n",
    "同样，我们应该先建好样例类，在main()方法中定义配置、创建SparkSession并加载数据，最后关闭spark。代码如下：\n",
    "\n",
    "`src/main/scala/com.atguigu.statistics/StatisticsRecommender.scala`\n",
    "\n",
    "```scala\n",
    "package com.atguigu.statistic\n",
    "\n",
    "import java.text.SimpleDateFormat\n",
    "import java.util.Date\n",
    "\n",
    "import org.apache.spark.SparkConf\n",
    "import org.apache.spark.sql.SparkSession\n",
    "\n",
    "case class Product(productId: Int, name: String, categories: String, imageUrl: String, tags: String)\n",
    "\n",
    "case class Rating(userId: Int, productId: Int, score: Double, timestamp: Int)\n",
    "\n",
    "case class MongoConfig(uri:String, db:String)\n",
    "\n",
    "case class Recommendation(rid: Int, r: Double)\n",
    "\n",
    "object StatisticRecommender {\n",
    "\n",
    "  val MONGODB_RATING_COLLECTION = \"Rating\"\n",
    "  val MONGODB_PRODUCT_COLLECTION = \"Products\"\n",
    "\n",
    "  //统计的表的名称\n",
    "  val RATE_MORE_PRODUCTS = \"RateMoreProducts\"\n",
    "  val RATE_MORE_RECENTLY_PRODUCTS = \"RateMoreRecentlyProducts\"\n",
    "  val AVERAGE_PRODUCTS = \"AverageProducts\"\n",
    "\n",
    "  // 入口方法\n",
    "  def main(args: Array[String]): Unit = {\n",
    "\n",
    "    val config = Map(\n",
    "      \"spark.cores\" -> \"local[*]\",\n",
    "      \"mongo.uri\" -> \"mongodb://localhost:27017/recommender\",\n",
    "      \"mongo.db\" -> \"recommender\"\n",
    "    )\n",
    "\n",
    "    // 创建SparkConf配置\n",
    "    val sparkConf = new SparkConf().setAppName(\"StatisticRecommender\").setMaster(config(\"spark.cores\"))\n",
    "\n",
    "    // 创建SparkSession\n",
    "    val spark = SparkSession.builder().config(sparkConf).getOrCreate()\n",
    "\n",
    "    // 调高日志等级\n",
    "    spark.sparkContext.setLogLevel(\"ERROR\")\n",
    "\n",
    "    val mongoConfig = MongoConfig(config(\"mongo.uri\"),config(\"mongo.db\"))\n",
    "\n",
    "    //加入隐式转换\n",
    "    import spark.implicits._\n",
    "\n",
    "    //数据加载进来\n",
    "    val ratingDF = spark\n",
    "      .read\n",
    "      .option(\"uri\", mongoConfig.uri)\n",
    "      .option(\"collection\", MONGODB_RATING_COLLECTION)\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .load()\n",
    "      .as[Rating]\n",
    "      .toDF()\n",
    "\n",
    "    val productDF = spark\n",
    "      .read\n",
    "      .option(\"uri\", mongoConfig.uri)\n",
    "      .option(\"collection\", MONGODB_PRODUCT_COLLECTION)\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .load()\n",
    "      .as[Product]\n",
    "      .toDF()\n",
    "\n",
    "    ratingDF.createOrReplaceTempView(\"ratings\")\n",
    "\n",
    "    val rateMoreProductsDF = spark.sql(\"select productId, count(productId) as count from ratings group by productId\")\n",
    "\n",
    "    rateMoreProductsDF\n",
    "      .write\n",
    "      .option(\"uri\", mongoConfig.uri)\n",
    "      .option(\"collection\", RATE_MORE_PRODUCTS)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "\n",
    "    val simpleDateFormat = new SimpleDateFormat(\"yyyyMM\")\n",
    "\n",
    "    spark.udf.register(\"changeDate\", (x: Int) => simpleDateFormat.format(new Date(x * 1000L)).toInt)\n",
    "\n",
    "    val ratingOfYearMonth = spark.sql(\"select productId, score, changeDate(timestamp) as yearmonth from ratings\")\n",
    "\n",
    "    ratingOfYearMonth.createOrReplaceTempView(\"ratingOfMonth\")\n",
    "\n",
    "    val rateMoreRecentlyProducts = spark.sql(\"select productId, count(productId) as count, yearmonth from ratingOfMonth group by yearmonth, productId\")\n",
    "\n",
    "    rateMoreRecentlyProducts\n",
    "      .write\n",
    "      .option(\"uri\",mongoConfig.uri)\n",
    "      .option(\"collection\",RATE_MORE_RECENTLY_PRODUCTS)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "\n",
    "    val averageProductsDF = spark.sql(\"select productId, avg(score) as avg from ratings group by productId order by avg desc\")\n",
    "\n",
    "    averageProductsDF.show()\n",
    "\n",
    "    averageProductsDF\n",
    "      .write\n",
    "      .option(\"uri\",mongoConfig.uri)\n",
    "      .option(\"collection\",AVERAGE_PRODUCTS)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "\n",
    "    //关闭Spark\n",
    "    spark.stop()\n",
    "  }\n",
    "}\n",
    "```\n",
    "\n",
    "## 4.2 离线统计服务\n",
    "\n",
    "下面我们针对以上代码分开讲解：\n",
    "\n",
    "### 4.2.4 历史热门商品统计\n",
    "\n",
    "根据所有历史评分数据，计算历史评分次数最多的商品。\n",
    "\n",
    "实现思路：\n",
    "\n",
    "通过Spark SQL读取评分数据集，统计所有评分中评分数最多的商品，然后按照从大到小排序，将最终结果写入MongoDB的RateMoreProducts数据集中。\n",
    "\n",
    "```scala\n",
    "//统计所有历史数据中每个商品的评分数\n",
    "//数据结构 ->  productId,count\n",
    "val rateMoreProductsDF = spark.sql(\"select productId, count(productId) as count from ratings group by productId\")\n",
    "\n",
    "rateMoreProductsDF\n",
    "    .write\n",
    "    .option(\"uri\", mongoConfig.uri)\n",
    "    .option(\"collection\", RATE_MORE_PRODUCTS)\n",
    "    .mode(\"overwrite\")\n",
    "    .format(\"com.mongodb.spark.sql\")\n",
    "    .save()\n",
    "```\n",
    "\n",
    "### 4.2.2 最近热门商品统计\n",
    "\n",
    "根据评分，按月为单位计算最近时间的月份里面评分数最多的商品集合。\n",
    "\n",
    "实现思路：\n",
    "\n",
    "通过Spark SQL读取评分数据集，通过UDF函数将评分的数据时间修改为月，然后统计每月商品的评分数。统计完成之后将数据写入到MongoDB的RateMoreRecentlyProducts数据集中。\n",
    "\n",
    "```scala\n",
    "//统计以月为单位拟每个电商的评分数\n",
    "//数据结构 -> productId,count,time\n",
    "\n",
    "//创建一个日期格式化工具\n",
    "val simpleDateFormat = new SimpleDateFormat(\"yyyyMM\")\n",
    "\n",
    "//注册一个UDF函数，用于将timestamp装换成年月格式   1260759144000  => 201605\n",
    "spark.udf.register(\"changeDate\", (x: Int) => simpleDateFormat.format(new Date(x * 1000L)).toInt)\n",
    "\n",
    "// 将原来的Rating数据集中的时间转换成年月的格式\n",
    "val ratingOfYearMonth = spark.sql(\"select productId, score, changeDate(timestamp) as yearmonth from ratings\")\n",
    "\n",
    "// 将新的数据集注册成为一张表\n",
    "ratingOfYearMonth.createOrReplaceTempView(\"ratingOfMonth\")\n",
    "\n",
    "val rateMoreRecentlyProducts = spark.sql(\"select productId, count(productId) as count, yearmonth from ratingOfMonth group by yearmonth, productId\")\n",
    "\n",
    "rateMoreRecentlyProducts\n",
    "    .write\n",
    "    .option(\"uri\",mongoConfig.uri)\n",
    "    .option(\"collection\",RATE_MORE_RECENTLY_PRODUCTS)\n",
    "    .mode(\"overwrite\")\n",
    "    .format(\"com.mongodb.spark.sql\")\n",
    "    .save()\n",
    "```\n",
    "\n",
    "### 4.2.3 商品平均得分统计\n",
    "\n",
    "根据历史数据中所有用户对商品的评分，周期性的计算每个商品的平均得分。\n",
    "\n",
    "实现思路：\n",
    "\n",
    "通过Spark SQL读取保存在MongDB中的Rating数据集，通过执行以下SQL语句实现对于商品的平均分统计：\n",
    "\n",
    "```scala\n",
    "val averageProductsDF = spark.sql(\"select productId, avg(score) as avg from ratings group by productId order by avg desc\")\n",
    "\n",
    "averageProductsDF.show()\n",
    "\n",
    "averageProductsDF\n",
    "    .write\n",
    "    .option(\"uri\",mongoConfig.uri)\n",
    "    .option(\"collection\",AVERAGE_PRODUCTS)\n",
    "    .mode(\"overwrite\")\n",
    "    .format(\"com.mongodb.spark.sql\")\n",
    "    .save()\n",
    "```\n",
    "\n",
    "## 4.3 基于隐语义模型的协同过滤推荐\n",
    "\n",
    "项目采用ALS作为协同过滤算法，分别根据MongoDB中的用户评分表和商品数据集计算用户商品推荐矩阵以及商品相似度矩阵。\n",
    "\n",
    "4.3.1 用户商品推荐矩阵\n",
    "\n",
    "通过ALS训练出来的Model来计算所有当前用户电商的推荐矩阵，主要思路如下：\n",
    "\n",
    "1.\tUserId和ProductID做笛卡尔积，产生（userId，productId）的元组\n",
    "2.\t通过模型预测（userId，productId）的元组。\n",
    "3.\t将预测结果通过预测分值进行排序。\n",
    "4.\t返回分值最大的K个电商，作为当前用户的推荐。\n",
    "\n",
    "最后生成的数据结构如下：将数据保存到MongoDB的UserRecs表中\n",
    "\n",
    "**图略**\n",
    "\n",
    "新建recommender的子项目OfflineRecommender，引入spark、scala、mongo和jblas的依赖：\n",
    "\n",
    "```xml\n",
    "    <dependencies>\n",
    "\n",
    "        <dependency>\n",
    "            <groupId>org.scalanlp</groupId>\n",
    "            <artifactId>jblas</artifactId>\n",
    "            <version>${jblas.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <!-- Spark的依赖引入 -->\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-core_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-sql_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-mllib_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <!-- 引入Scala -->\n",
    "        <dependency>\n",
    "            <groupId>org.scala-lang</groupId>\n",
    "            <artifactId>scala-library</artifactId>\n",
    "            <version>${scala.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <!-- 加入MongoDB的驱动 -->\n",
    "        <!-- 用于代码方式连接MongoDB -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb</groupId>\n",
    "            <artifactId>casbah-core_2.11</artifactId>\n",
    "            <version>${casbah.version}</version>\n",
    "        </dependency>\n",
    "        <!-- 用于Spark和MongoDB的对接 -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb.spark</groupId>\n",
    "            <artifactId>mongo-spark-connector_2.11</artifactId>\n",
    "            <version>${mongodb-spark.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "    </dependencies>\n",
    "```\n",
    "\n",
    "同样经过前期的构建样例类、声明配置、创建SparkSession等步骤，可以加载数据开始计算模型了。核心代码如下：\n",
    "\n",
    "`src/main/scala/com.atguigu.offline/OfflineRecommender.scala`\n",
    "\n",
    "```scala\n",
    "package com.atguigu.offline\n",
    "\n",
    "import org.apache.spark.SparkConf\n",
    "import org.apache.spark.mllib.recommendation.{ALS, Rating}\n",
    "import org.apache.spark.sql.SparkSession\n",
    "import org.jblas.DoubleMatrix\n",
    "\n",
    "case class Product(productId: Int, name: String, categories: String, imageUrl: String, tags: String)\n",
    "\n",
    "case class ProductRating(userId: Int, productId: Int, score: Double, timestamp: Int)\n",
    "\n",
    "case class MongoConfig(uri: String, db: String)\n",
    "\n",
    "case class Recommendation(rid: Int, r: Double)\n",
    "\n",
    "case class UserRecs(userId: Int, recs: Seq[Recommendation])\n",
    "\n",
    "case class ProductRecs(productId: Int, recs: Seq[Recommendation])\n",
    "\n",
    "object OfflineRecommender {\n",
    "\n",
    "  val MONGODB_RATING_COLLECTION = \"Rating\"\n",
    "  val MONGODB_PRODUCT_COLLECTION = \"Products\"\n",
    "\n",
    "  val USER_MAX_RECOMMENDATION = 20\n",
    "\n",
    "  val USER_RECS = \"UserRecs\"\n",
    "  val PRODUCT_RECS = \"ProductRecs\"\n",
    "\n",
    "  //入口方法\n",
    "  def main(args: Array[String]): Unit = {\n",
    "\n",
    "    val config = Map(\n",
    "      \"spark.cores\" -> \"local[*]\",\n",
    "      \"mongo.uri\" -> \"mongodb://localhost:27017/recommender\",\n",
    "      \"mongo.db\" -> \"reommender\"\n",
    "    )\n",
    "\n",
    "    //创建一个SparkConf配置\n",
    "    val sparkConf = new SparkConf().setAppName(\"OfflineRecommender\").setMaster(config(\"spark.cores\")).set(\"spark.executor.memory\",\"6G\").set(\"spark.driver.memory\",\"2G\")\n",
    "\n",
    "    //基于SparkConf创建一个SparkSession\n",
    "    val spark = SparkSession.builder().config(sparkConf).getOrCreate()\n",
    "\n",
    "    spark.sparkContext.setLogLevel(\"ERROR\")\n",
    "\n",
    "    //创建一个MongoDBConfig\n",
    "    val mongoConfig = MongoConfig(config(\"mongo.uri\"),config(\"mongo.db\"))\n",
    "\n",
    "    import spark.implicits._\n",
    "\n",
    "    // 读取mongoDB中的业务数据\n",
    "    val ratingRDD = spark\n",
    "      .read\n",
    "      .option(\"uri\",mongoConfig.uri)\n",
    "      .option(\"collection\",MONGODB_RATING_COLLECTION)\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .load()\n",
    "      .as[ProductRating]\n",
    "      .rdd\n",
    "      .map(rating => (rating.userId, rating.productId, rating.score)).cache()\n",
    "\n",
    "    //用户的数据集 RDD[Int]\n",
    "    val userRDD = ratingRDD.map(_._1).distinct()\n",
    "\n",
    "    //电影数据集 RDD[Int]\n",
    "    val productRDD = spark\n",
    "      .read\n",
    "      .option(\"uri\",mongoConfig.uri)\n",
    "      .option(\"collection\",MONGODB_PRODUCT_COLLECTION)\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .load()\n",
    "      .as[Product]\n",
    "      .rdd\n",
    "      .map(_.productId).cache()\n",
    "\n",
    "    //创建训练数据集\n",
    "\n",
    "    val trainData = ratingRDD.map(x => Rating(x._1,x._2,x._3))\n",
    "\n",
    "    // r: M x N\n",
    "    // u: M x K\n",
    "    // i: K x N\n",
    "    val (rank,iterations,lambda) = (50, 5, 0.01)\n",
    "    //训练ALS模型\n",
    "    val model = ALS.train(trainData,rank,iterations,lambda)\n",
    "\n",
    "    //计算用户推荐矩阵\n",
    "\n",
    "    //需要构造一个usersProducts  RDD[(Int,Int)]\n",
    "    val userProducts = userRDD.cartesian(productRDD)\n",
    "\n",
    "    val preRatings = model.predict(userProducts)\n",
    "\n",
    "    val userRecs = preRatings\n",
    "      .filter(_.rating > 0)\n",
    "      .map(rating => (rating.user, (rating.product, rating.rating)))\n",
    "      .groupByKey()\n",
    "      .map{\n",
    "        case (userId,recs) => UserRecs(userId, recs.toList.sortWith(_._2 > _._2).take(USER_MAX_RECOMMENDATION).map(x => Recommendation(x._1,x._2)))\n",
    "      }.toDF()\n",
    "\n",
    "    userRecs.write\n",
    "      .option(\"uri\",mongoConfig.uri)\n",
    "      .option(\"collection\",USER_RECS)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "\n",
    "    val productFeatures = model.productFeatures.map{case (productId, features) =>\n",
    "      (productId, new DoubleMatrix(features))\n",
    "    }\n",
    "\n",
    "    val productRecs = productFeatures.cartesian(productFeatures)\n",
    "      .filter{case (a,b) => a._1 != b._1}\n",
    "      .map{case (a,b) =>\n",
    "        val simScore = this.consinSim(a._2,b._2)\n",
    "        (a._1,(b._1,simScore))\n",
    "      }.filter(_._2._2 > 0.6)\n",
    "      .groupByKey()\n",
    "      .map{case (productId, items) =>\n",
    "        ProductRecs(productId, items.toList.map(x => Recommendation(x._1,x._2)))\n",
    "      }.toDF()\n",
    "\n",
    "    productRecs\n",
    "      .write\n",
    "      .option(\"uri\", mongoConfig.uri)\n",
    "      .option(\"collection\",PRODUCT_RECS)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "\n",
    "    spark.close()\n",
    "  }\n",
    "\n",
    "  def consinSim(product1: DoubleMatrix, product2: DoubleMatrix) : Double ={\n",
    "    product1.dot(product2) / ( product1.norm2()  * product2.norm2() )\n",
    "  }\n",
    "}\n",
    "```\n",
    "\n",
    "### 4.3.2 商品相似度矩阵\n",
    "\n",
    "通过ALS计算商品间相似度矩阵，该矩阵用于查询当前电商的相似电商并为实时推荐系统服务。\n",
    "\n",
    "离线计算的ALS算法，算法最终会为用户、商品分别生成最终的特征矩阵，分别是表示用户特征矩阵的U(M x K)矩阵，每个用户由K个特征描述；表示物品特征矩阵的V(N x K)矩阵，每个物品也由K个特征描述。\n",
    "\n",
    "V(N x K)表示物品特征矩阵，每一行是一个K维向量，虽然我们并不知道每一个维度的特征意义是什么，但是K个维度的数学向量表示了该行对应电商的特征。\n",
    "\n",
    "所以，每个商品用$V_{N \\times K}$每一行的$(t_1, \\dots, t_K)$向量表示其特征。\n",
    "\n",
    "于是任意两个商品\n",
    "\n",
    "p: 特征向量为$V_p=(t_{p1}, \\dots, t_{pk})$\n",
    "\n",
    "q: 特征向量为$V_q=(t_{q1}, \\dots, t_{qk})$\n",
    "\n",
    "之间的相似度$sim(p, q)$可以使用$V_p$和$V_q$的余弦值来表示: \n",
    "\n",
    "$$\n",
    "sim(p,q)=\\frac{\\sum_{i=0}^k(t_{pi} \\times t_{qi})}{\\sqrt{\\sum_{i=0}^kt_{pi}^2} \\times \\sqrt{\\sum_{i=0}^kt_{qi}^2}}\n",
    "$$\n",
    "\n",
    "数据集中任意两个商品间相似度都可以由公式计算得到，商品与商品之间的相似度在一段时间内基本是固定值。最后生成的数据保存到MongoDB的ProductRecs表中。\n",
    "\n",
    "**图略**\n",
    "\n",
    "核心代码如下：\n",
    "\n",
    "```scala\n",
    "    val productFeatures = model.productFeatures.map{case (productId, features) =>\n",
    "      (productId, new DoubleMatrix(features))\n",
    "    }\n",
    "\n",
    "    val productRecs = productFeatures.cartesian(productFeatures)\n",
    "      .filter{case (a,b) => a._1 != b._1}\n",
    "      .map{case (a,b) =>\n",
    "        val simScore = this.consinSim(a._2,b._2)\n",
    "        (a._1,(b._1,simScore))\n",
    "      }.filter(_._2._2 > 0.6)\n",
    "      .groupByKey()\n",
    "      .map{case (productId, items) =>\n",
    "        ProductRecs(productId, items.toList.map(x => Recommendation(x._1,x._2)))\n",
    "      }.toDF()\n",
    "\n",
    "    productRecs\n",
    "      .write\n",
    "      .option(\"uri\", mongoConfig.uri)\n",
    "      .option(\"collection\",PRODUCT_RECS)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "```\n",
    "\n",
    "其中，consinSim是求两个向量余弦相似度的函数，代码实现如下：\n",
    "\n",
    "```scala\n",
    "  def consinSim(product1: DoubleMatrix, product2: DoubleMatrix) : Double ={\n",
    "    product1.dot(product2) / ( product1.norm2()  * product2.norm2() )\n",
    "  }\n",
    "```\n",
    "\n",
    "### 4.3.3 模型评估和参数选取\n",
    "\n",
    "在上述模型训练的过程中，我们直接给定了隐语义模型的rank, iterations, lambda三个参数。对于我们的模型，这并不一定是最优的参数选取，所以我们需要对模型进行评估。通常的做法是计算均方根误差（RMSE），考察预测评分与实际评分之间的误差。\n",
    "\n",
    "$$\n",
    "RMSE=\\sqrt {\\frac{1}{N}\\sum_{t=1}^N(observed_t-predicted_t)^2}\n",
    "$$\n",
    "\n",
    "有了RMSE，我们可以就可以通过多次调整参数值，来选取RMSE最小的一组作为我们模型的优化选择。\n",
    "\n",
    "在scala/com.atguigu.offline/下新建单例对象ALSTrainer，代码主体架构如下：\n",
    "\n",
    "```scala\n",
    "package com.atguigu.offline\n",
    "\n",
    "import breeze.numerics.sqrt\n",
    "import org.apache.spark.SparkConf\n",
    "import org.apache.spark.mllib.recommendation.{ALS, MatrixFactorizationModel, Rating}\n",
    "import org.apache.spark.rdd.RDD\n",
    "import org.apache.spark.sql.SparkSession\n",
    "\n",
    "object ALSTrainer {\n",
    "\n",
    "  def main(args: Array[String]): Unit = {\n",
    "\n",
    "    val config = Map(\n",
    "      \"spark.cores\" -> \"local[*]\",\n",
    "      \"mongo.uri\" -> \"mongodb://localhost:27017/recommender\",\n",
    "      \"mongo.db\" -> \"recommender\"\n",
    "    )\n",
    "\n",
    "    //创建SparkConf\n",
    "    val sparkConf = new SparkConf().setAppName(\"ALSTrainer\").setMaster(config(\"spark.cores\"))\n",
    "\n",
    "    //创建SparkSession\n",
    "    val spark = SparkSession.builder().config(sparkConf).getOrCreate()\n",
    "\n",
    "    val mongoConfig = MongoConfig(config(\"mongo.uri\"),config(\"mongo.db\"))\n",
    "\n",
    "    import spark.implicits._\n",
    "\n",
    "    //加载评分数据\n",
    "    val ratingRDD = spark\n",
    "      .read\n",
    "      .option(\"uri\",mongoConfig.uri)\n",
    "      .option(\"collection\",OfflineRecommender.MONGODB_RATING_COLLECTION)\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .load()\n",
    "      .as[ProductRating]\n",
    "      .rdd\n",
    "      .map(rating => Rating(rating.userId, rating.productId, rating.score)).cache()\n",
    "\n",
    "    // 训练集的数据量是80%，测试集的数量是20%\n",
    "    val splits = ratingRDD.randomSplit(Array(0.8, 0.2))\n",
    "\n",
    "    val trainingRDD = splits(0)\n",
    "    val testingRDD = splits(1)\n",
    "\n",
    "    //输出最优参数\n",
    "    adjustALSParams(trainingRDD, testingRDD)\n",
    "\n",
    "    //关闭Spark\n",
    "    spark.close()\n",
    "  }\n",
    "\n",
    "  // 输出最终的最优参数\n",
    "  def adjustALSParams(trainData:RDD[Rating], testData:RDD[Rating]): Unit ={\n",
    "    val result = for(rank <- Array(30,40,50,60,70); lambda <- Array(1, 0.1, 0.001))\n",
    "      yield {\n",
    "        val model = ALS.train(trainData,rank,5,lambda)\n",
    "        val rmse = getRmse(model, testData)\n",
    "        (rank,lambda,rmse)\n",
    "      }\n",
    "    println(result.sortBy(_._3).head)\n",
    "  }\n",
    "\n",
    "  def getRmse(model: MatrixFactorizationModel, testData: RDD[Rating]):Double={\n",
    "    //需要构造一个usersProducts  RDD[(Int,Int)]\n",
    "    val userProducts = testData.map(item => (item.user,item.product))\n",
    "    val predictRating = model.predict(userProducts)\n",
    "\n",
    "    val real = testData.map(item => ((item.user,item.product),item.rating))\n",
    "    val predict = predictRating.map(item => ((item.user,item.product),item.rating))\n",
    "\n",
    "    sqrt(\n",
    "      real.join(predict).map{case ((uid,mid),(real,pre))=>\n",
    "        // 真实值和预测值之间的两个差值\n",
    "        val err = real - pre\n",
    "        err * err\n",
    "      }.mean()\n",
    "    )\n",
    "  }\n",
    "}\n",
    "```\n",
    "\n",
    "其中adjustALSParams方法是模型评估的核心，输入一组训练数据和测试数据，输出计算得到最小RMSE的那组参数。代码实现如下：\n",
    "\n",
    "```scala\n",
    "  // 输出最终的最优参数\n",
    "  def adjustALSParams(trainData:RDD[Rating], testData:RDD[Rating]): Unit = {\n",
    "    // 这里指定迭代次数为5，rank和lambda在几个值中选取调整\n",
    "    val result = for(rank <- Array(30, 40, 50, 60, 70); lambda <- Array(1, 0.1, 0.001))\n",
    "      yield {\n",
    "        val model = ALS.train(trainData, rank, 5, lambda)\n",
    "        val rmse = getRmse(model, testData)\n",
    "        (rank,lambda,rmse)\n",
    "      }\n",
    "    println(result.sortBy(_._3).head)\n",
    "  }\n",
    "```\n",
    "\n",
    "计算RMSE的函数getRMSE代码实现如下：\n",
    "\n",
    "```scala\n",
    "  def getRmse(model: MatrixFactorizationModel, testData: RDD[Rating]): Double = {\n",
    "    //需要构造一个usersProducts  RDD[(Int,Int)]\n",
    "    val userProducts = testData.map(item => (item.user,item.product))\n",
    "    val predictRating = model.predict(userProducts)\n",
    "\n",
    "    val real = testData.map(item => ((item.user,item.product),item.rating))\n",
    "    val predict = predictRating.map(item => ((item.user,item.product),item.rating))\n",
    "\n",
    "    sqrt(\n",
    "      real.join(predict).map{case ((uid,mid),(real,pre))=>\n",
    "        // 真实值和预测值之间的两个差值\n",
    "        val err = real - pre\n",
    "        err * err\n",
    "      }.mean()\n",
    "    )\n",
    "  }\n",
    "```\n",
    "\n",
    "运行代码，我们就可以得到目前数据的最优模型的超参数。\n",
    "\n",
    "# 第5章 实时推荐服务建设\n",
    "\n",
    "## 5.1 实时推荐服务\n",
    "\n",
    "实时计算与离线计算应用于推荐系统上最大的不同在于实时计算推荐结果应该反映最近一段时间用户近期的偏好，而离线计算推荐结果则是根据用户从第一次评分起的所有评分记录来计算用户总体的偏好。\n",
    "\n",
    "用户对物品的偏好随着时间的推移总是会改变的。比如一个用户u在某时刻对商品p给予了极高的评分，那么在近期一段时候，u极有可能很喜欢与商品p类似的其他商品; 而如果用户u在某时刻对商品q给予了极低的评分，那么在近期一段时候，u极有可能不喜欢与商品q类似的其他商品。所以对于实时推荐，当用户对一个电商进行了评价后，用户会希望推荐结果基于最近这几次评分进行一定的更新，使得推荐结果匹配用户近期的偏好，满足用户近期的口味。\n",
    "\n",
    "如果实时推荐继续采用离线推荐中的ALS算法，由于算法运行时间巨大，不具有实时得到新的推荐结果的能力；并且由于算法本身的使用的是评分表，用户本次评分后只更新了总评分表中的一项，使得算法运行后的推荐结果与用户本次评分之前的推荐结果基本没有多少差别，从而给用户一种推荐结果一直没变化的感觉，很影响用户体验。\n",
    "\n",
    "另外，在实时推荐中由于时间性能上要满足实时或者准实时的要求，所以算法的计算量不能太大，避免复杂、过多的计算造成用户体验的下降。鉴于此，推荐精度往往不会很高。实时推荐系统更关心推荐结果的动态变化能力，只要更新推荐结果的理由合理即可，至于推荐的精度要求则可以适当放宽。\n",
    "\n",
    "所以对于实时推荐算法，主要有两点需求：\n",
    "\n",
    "1. 用户本次评分后、或最近几个评分后系统可以明显的更新推荐结果；\n",
    "2. 计算量不大，满足响应时间上的实时或者准实时要求；\n",
    "\n",
    "## 5.2 实时推荐算法设计\n",
    "\n",
    "当用户u对商品p进行了评分，将触发一次对u的推荐结果的更新。由于用户u对商品p评分，对于用户u来说，他与p最相似的商品们之间的推荐强度将发生变化，所以选取与商品p最相似的K个商品作为候选商品。\n",
    "\n",
    "每个候选商品按照“推荐优先级”这一权重作为衡量这个商品被推荐给用户u的优先级。\n",
    "\n",
    "这些商品将根据用户u最近的若干评分计算出各自对用户u的推荐优先级，然后与上次对用户u的实时推荐结果的进行基于推荐优先级的合并、替换得到更新后的推荐结果。\n",
    "\n",
    "具体来说：\n",
    "\n",
    "首先，获取用户u按时间顺序最近的K个评分，记为$R_K$；获取商品p的最相似的K个商品集合，记为S；\n",
    "\n",
    "然后，对于每个商品q属于S，计算其推荐优先级$E_{uq}$，计算公式如下：\n",
    "\n",
    "$$\n",
    "E_{uq}=\\frac{\\sum_{r \\in R_K}sim(q,r)\\times R_r}{sim \\underline\\space sum} + log_2max(incount, 1) - log_2max(recount, 1)\n",
    "$$\n",
    "\n",
    "其中：\n",
    "- $R_r$表示用户u对商品r的评分；\n",
    "- sim(q,r)表示商品q与商品r的相似度，设定最小相似度为0.6，当商品q和商品r相似度低于0.6的阈值，则视为两者不相关并忽略；\n",
    "- sim_sum表示q与$R_K$中商品相似度大于最小阈值的个数；\n",
    "- incount表示$R_K$中与商品q相似的、且本身评分较高（>=3）的商品个数；\n",
    "- recount表示$R_K$中与商品q相似的、且本身评分较低（<3）的商品个数；\n",
    "\n",
    "公式的意义如下：\n",
    "\n",
    "首先对于每个候选商品q，从u最近的K个评分中，找出与q相似度较高（>=0.6）的u已评分商品们，对于这些商品们中的每个商品r，将r与q的相似度乘以用户u对r的评分，将这些乘积计算平均数，作为用户u对商品q的评分预测即\n",
    "\n",
    "$$\n",
    "\\frac{\\sum_{r \\in R_K}sim(q,r)\\times R_r}{sim \\underline\\space sum}\n",
    "$$\n",
    "\n",
    "然后，将u最近的K个评分中与商品q相似的、且本身评分较高（>=3）的商品个数记为incount，计算lgmax{incount, 1}作为商品q的“增强因子”，意义在于商品q与u的最近K个评分中的n个高评分(>=3)商品相似，则商品q的优先级被增加lgmax{incount, 1}。如果商品q与u的最近K个评分中相似的高评分商品越多，也就是说n越大，则商品q更应该被推荐，所以推荐优先级被增强的幅度较大；如果商品q与u的最近K个评分中相似的高评分商品越少，也就是n越小，则推荐优先级被增强的幅度较小；\n",
    "\n",
    "而后，将u最近的K个评分中与商品q相似的、且本身评分较低（<3）的商品个数记为recount，计算lgmax{recount, 1}作为商品q的“削弱因子”，意义在于商品q与u的最近K个评分中的n个低评分(<3)商品相似，则商品q的优先级被削减lgmax{incount, 1}。如果商品q与u的最近K个评分中相似的低评分商品越多，也就是说n越大，则商品q更不应该被推荐，所以推荐优先级被减弱的幅度较大；如果商品q与u的最近K个评分中相似的低评分商品越少，也就是n越小，则推荐优先级被减弱的幅度较小；\n",
    "\n",
    "最后，将增强因子增加到上述的预测评分中，并减去削弱因子，得到最终的q商品对于u的推荐优先级。在计算完每个候选商品q的E<sub>uq</sub>后，将生成一组<商品q的ID, q的推荐优先级>的列表updatedList：\n",
    "\n",
    "$$\n",
    "updatedList = \\bigcup\\limits_{q \\in S}(qID, E_{uq})\n",
    "$$\n",
    "\n",
    "而在本次为用户u 实时推荐之前的上一次实时推荐结果Rec 也是一组<商品m,m 的推荐优先级>的列表，其大小也为K：\n",
    "\n",
    "$$\n",
    "Rec=\\bigcup\\limits_{m \\in Rec}(mID, E_{um}); len(Rec)==K;\n",
    "$$\n",
    "\n",
    "接下来，将updated_S 与本次为u 实时推荐之前的上一次实时推荐结果Rec进行基于合并、替换形成新的推荐结果NewRec：\n",
    "\n",
    "$$\n",
    "New \\space Rec = topK(i\\in Rec \\bigcup updatedList, cmp=E_{ui})\n",
    "$$\n",
    "\n",
    "其中，i表示updated_S与Rec的商品集合中的每个商品，topK是一个函数，表示从Rec和updated_S的并集中选择出最大的K个商品，cmp=E<sub>ui</sub>表示topK函数将推荐优先级E<sub>ui</sub>值最大的K个商品选出来。最终，NewRec即为经过用户u对商品p评分后触发的实时推荐得到的最新推荐结果。\n",
    "\n",
    "总之，实时推荐算法流程流程基本如下：\n",
    "\n",
    "1. 用户u 对商品p 进行了评分，触发了实时推荐的一次计算；\n",
    "2. 选出商品p 最相似的K 个商品作为集合S；\n",
    "3. 获取用户u 最近时间内的K 条评分，包含本次评分，作为集合RK；\n",
    "4. 计算商品的推荐优先级，产生(q<sub>ID</sub>, E<sub>uq</sub>)集合updated_S；\n",
    "\n",
    "将updated_S 与上次对用户u 的推荐结果Rec 利用公式(4-4)进行合并，产生新的推荐结果NewRec；作为最终输出。\n",
    "\n",
    "我们在recommender下新建子项目StreamingRecommender，引入spark、scala、mongo、redis和kafka的依赖:\n",
    "\n",
    "```xml\n",
    "    <dependencies>\n",
    "        <!-- Spark的依赖引入 -->\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-core_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-sql_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-streaming_2.11</artifactId>\n",
    "        </dependency>\n",
    "        <!-- 引入Scala -->\n",
    "        <dependency>\n",
    "            <groupId>org.scala-lang</groupId>\n",
    "            <artifactId>scala-library</artifactId>\n",
    "            <version>${scala.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <!-- 加入MongoDB的驱动 -->\n",
    "        <!-- 用于代码方式连接MongoDB -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb</groupId>\n",
    "            <artifactId>casbah-core_2.11</artifactId>\n",
    "            <version>${casbah.version}</version>\n",
    "        </dependency>\n",
    "        <!-- 用于Spark和MongoDB的对接 -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb.spark</groupId>\n",
    "            <artifactId>mongo-spark-connector_2.11</artifactId>\n",
    "            <version>${mongodb-spark.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <!-- redis -->\n",
    "        <dependency>\n",
    "            <groupId>redis.clients</groupId>\n",
    "            <artifactId>jedis</artifactId>\n",
    "            <version>2.9.0</version>\n",
    "        </dependency>\n",
    "\n",
    "        <!-- kafka -->\n",
    "        <dependency>\n",
    "            <groupId>org.apache.kafka</groupId>\n",
    "            <artifactId>kafka-clients</artifactId>\n",
    "            <version>0.10.2.1</version>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-streaming-kafka-0-10_2.11</artifactId>\n",
    "            <version>${spark.version}</version>\n",
    "        </dependency>\n",
    "    </dependencies>\n",
    "```\n",
    "\n",
    "代码中首先定义样例类和一个连接助手对象（用于建立redis和mongo连接），并在StreamingRecommender中定义一些常量：\n",
    "\n",
    "`src/main/scala/com.atguigu.streaming/StreamingRecommender.scala`\n",
    "\n",
    "```scala\n",
    "package com.atguigu.streaming\n",
    "\n",
    "import com.mongodb.casbah.commons.MongoDBObject\n",
    "import com.mongodb.casbah.{MongoClient, MongoClientURI}\n",
    "import org.apache.kafka.common.serialization.StringDeserializer\n",
    "import org.apache.spark.SparkConf\n",
    "import org.apache.spark.sql.SparkSession\n",
    "import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}\n",
    "import org.apache.spark.streaming.{Seconds, StreamingContext}\n",
    "import redis.clients.jedis.Jedis\n",
    "\n",
    "import scala.collection.JavaConversions._\n",
    "\n",
    "object ConnHelper extends Serializable{\n",
    "  lazy val jedis = new Jedis(\"localhost\")\n",
    "  lazy val mongoClient = MongoClient(MongoClientURI(\"mongodb://localhost:27017/recommender\"))\n",
    "}\n",
    "\n",
    "case class MongConfig(uri: String, db: String)\n",
    "\n",
    "//推荐\n",
    "case class Recommendation(rid: Int, r: Double)\n",
    "\n",
    "// 用户的推荐\n",
    "case class UserRecs(uid: Int, recs: Seq[Recommendation])\n",
    "\n",
    "//商品的相似度\n",
    "case class ProductRecs(productId: Int, recs: Seq[Recommendation])\n",
    "\n",
    "object StreamingRecommender {\n",
    "\n",
    "  val MAX_USER_RATINGS_NUM = 20\n",
    "  val MAX_SIM_PRODUCTS_NUM = 20\n",
    "  val MONGODB_STREAM_RECS_COLLECTION = \"StreamRecs\"\n",
    "  val MONGODB_RATING_COLLECTION = \"Rating\"\n",
    "  val MONGODB_PRODUCT_RECS_COLLECTION = \"ProductRecs\"\n",
    "\n",
    "  //入口方法\n",
    "  def main(args: Array[String]): Unit = {\n",
    "\n",
    "    val config = Map(\n",
    "      \"spark.cores\" -> \"local[*]\",\n",
    "      \"mongo.uri\" -> \"mongodb://localhost:27017/recommender\",\n",
    "      \"mongo.db\" -> \"recommender\",\n",
    "      \"kafka.topic\" -> \"recommender\"\n",
    "    )\n",
    "    //创建一个SparkConf配置\n",
    "    val sparkConf = new SparkConf().setAppName(\"StreamingRecommender\").setMaster(config(\"spark.cores\"))\n",
    "\n",
    "    //创建Spark的对象, 因为spark session中没有封装streaming context，所以需要new一个\n",
    "    val spark = SparkSession.builder().config(sparkConf).getOrCreate()\n",
    "    val sc = spark.sparkContext\n",
    "    sc.setLogLevel(\"ERROR\")\n",
    "    val ssc = new StreamingContext(sc,Seconds(2))\n",
    "\n",
    "    implicit val mongConfig = MongConfig(config(\"mongo.uri\"),config(\"mongo.db\"))\n",
    "    import spark.implicits._\n",
    "\n",
    "    //******************  广播商品相似度矩阵\n",
    "\n",
    "    val simProductsMatrix = spark\n",
    "      .read\n",
    "      .option(\"uri\",config(\"mongo.uri\"))\n",
    "      .option(\"collection\",MONGODB_PRODUCT_RECS_COLLECTION)\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .load()\n",
    "      .as[ProductRecs]\n",
    "      .rdd\n",
    "      .map{recs =>\n",
    "        (recs.productId, recs.recs.map(x => (x.rid, x.r)).toMap)\n",
    "      }.collectAsMap()\n",
    "\n",
    "    val simProductsMatrixBroadCast = sc.broadcast(simProductsMatrix)\n",
    "\n",
    "    val abc = sc.makeRDD(1 to 2)\n",
    "    abc.map(x => simProductsMatrixBroadCast.value.get(1)).count()\n",
    "\n",
    "    //******************\n",
    "\n",
    "\n",
    "    //创建到Kafka的连接\n",
    "    val kafkaPara = Map(\n",
    "      \"bootstrap.servers\" -> \"localhost:9092\",\n",
    "      \"key.deserializer\" -> classOf[StringDeserializer],\n",
    "      \"value.deserializer\" -> classOf[StringDeserializer],\n",
    "      \"group.id\" -> \"recommender\",\n",
    "      \"auto.offset.reset\" -> \"latest\"    //每次从kafka 消费数据，都是通过zookeeper存储的数据offset，来判断需要获取消息在消息日志里的起始位置\n",
    "    )\n",
    "\n",
    "    val kafkaStream = KafkaUtils.createDirectStream[String,String](ssc,LocationStrategies.PreferConsistent,ConsumerStrategies.Subscribe[String,String](Array(config(\"kafka.topic\")),kafkaPara))\n",
    "\n",
    "    val ratingStream = kafkaStream.map{case msg =>\n",
    "      var attr = msg.value().split(\"\\\\|\")            // split方法对. | * + ^需要转义（类似正则）\n",
    "      (attr(0).toInt, attr(1).toInt, attr(2).toDouble, attr(3).toInt)\n",
    "    }\n",
    "\n",
    "    ratingStream.foreachRDD{rdd =>\n",
    "      rdd.map{case (userId, productId, score, timestamp) =>\n",
    "        println(\">>>>>>>>>>>>>>>>\")\n",
    "\n",
    "        //获取当前最近的M次商品评分\n",
    "        val userRecentlyRatings = getUserRecentlyRating(MAX_USER_RATINGS_NUM, userId, ConnHelper.jedis)\n",
    "\n",
    "        //获取商品P最相似的K个商品\n",
    "        val simProducts = getTopSimProducts(MAX_SIM_PRODUCTS_NUM, productId, userId, simProductsMatrixBroadCast.value)\n",
    "\n",
    "        //计算待选商品的推荐优先级\n",
    "        val streamRecs = computeProductScores(simProductsMatrixBroadCast.value, userRecentlyRatings, simProducts)\n",
    "\n",
    "        //将数据保存到MongoDB\n",
    "        saveRecsToMongoDB(userId, streamRecs)\n",
    "\n",
    "      }.count()\n",
    "    }\n",
    "\n",
    "    //启动Streaming程序\n",
    "    ssc.start()\n",
    "    ssc.awaitTermination()\n",
    "  }\n",
    "\n",
    "  def saveRecsToMongoDB(uid:Int,streamRecs:Array[(Int,Double)])(implicit mongConfig: MongConfig): Unit ={\n",
    "    //到StreamRecs的连接\n",
    "    val streamRecsCollection = ConnHelper.mongoClient(mongConfig.db)(MONGODB_STREAM_RECS_COLLECTION)\n",
    "\n",
    "    streamRecsCollection.findAndRemove(MongoDBObject(\"uid\" -> uid))\n",
    "    //streaRecsCollection.insert(MongoDBObject(\"uid\" -> uid, \"recs\" -> streamRecs.map(x=> x._1+\":\"+x._2).mkString(\"|\")))\n",
    "    streamRecsCollection.insert(MongoDBObject(\"uid\"->uid, \"recs\"-> streamRecs.map(x => MongoDBObject(\"mid\"->x._1, \"score\"->x._2)) ))\n",
    "\n",
    "  }\n",
    "\n",
    "  def computeProductScores(simProducts: scala.collection.Map[Int,scala.collection.immutable.Map[Int,Double]],userRecentlyRatings:Array[(Int,Double)],topSimProducts: Array[Int]): Array[(Int,Double)] = {\n",
    "\n",
    "    //用于保存每一个待选商品和最近评分的每一个商品的权重得分\n",
    "    val score = scala.collection.mutable.ArrayBuffer[(Int,Double)]()\n",
    "\n",
    "    //用于保存每一个商品的增强因子数\n",
    "    val increMap = scala.collection.mutable.HashMap[Int,Int]()\n",
    "\n",
    "    //用于保存每一个商品的减弱因子数\n",
    "    val decreMap = scala.collection.mutable.HashMap[Int,Int]()\n",
    "\n",
    "    for (topSimProduct <- topSimProducts; userRecentlyRating <- userRecentlyRatings){\n",
    "      val simScore = getProductsSimScore(simProducts, userRecentlyRating._1, topSimProduct)\n",
    "      if(simScore > 0.6){\n",
    "        score += ((topSimProduct, simScore * userRecentlyRating._2 ))\n",
    "        if(userRecentlyRating._2 > 3){\n",
    "          increMap(topSimProduct) = increMap.getOrDefault(topSimProduct,0) + 1\n",
    "        }else{\n",
    "          decreMap(topSimProduct) = decreMap.getOrDefault(topSimProduct,0) + 1\n",
    "        }\n",
    "      }\n",
    "    }\n",
    "\n",
    "    score.groupBy(_._1).map{case (mid,sims) =>\n",
    "      (mid,sims.map(_._2).sum / sims.length + log(increMap.getOrDefault(mid, 1)) - log(decreMap.getOrDefault(mid, 1)))\n",
    "    }.toArray\n",
    "\n",
    "  }\n",
    "\n",
    "  //取2的对数\n",
    "  def log(m: Int): Double ={\n",
    "    math.log(m) / math.log(2)\n",
    "  }\n",
    "\n",
    "  def getProductsSimScore(simProducts: scala.collection.Map[Int,scala.collection.immutable.Map[Int,Double]], userRatingProduct: Int, topSimProduct: Int): Double ={\n",
    "    simProducts.get(topSimProduct) match {\n",
    "      case Some(sim) => sim.get(userRatingProduct) match {\n",
    "        case Some(score) => score\n",
    "        case None => 0.0\n",
    "      }\n",
    "      case None => 0.0\n",
    "    }\n",
    "  }\n",
    "\n",
    "  def getTopSimProducts(num: Int, productId: Int, userId: Int, simProducts:scala.collection.Map[Int,scala.collection.immutable.Map[Int,Double]])(implicit mongConfig: MongConfig): Array[Int] ={\n",
    "    //从广播变量的商品相似度矩阵中获取当前商品所有的相似商品\n",
    "    val allSimProducts = simProducts(productId).toArray\n",
    "    //获取用户已经观看过得商品\n",
    "    val ratingExist = ConnHelper.mongoClient(mongConfig.db)(MONGODB_RATING_COLLECTION).find(MongoDBObject(\"userId\" -> userId)).toArray.map{item =>\n",
    "      item.get(\"productId\").toString.toInt\n",
    "    }\n",
    "    //过滤掉已经评分过得商品，并排序输出\n",
    "    allSimProducts.filter(x => !ratingExist.contains(x._1)).sortWith(_._2 > _._2).take(num).map(x => x._1)\n",
    "  }\n",
    "\n",
    "  def getUserRecentlyRating(num: Int, userId: Int, jedis: Jedis): Array[(Int, Double)] ={\n",
    "    //从用户的队列中取出num个评论\n",
    "    jedis.lrange(\"userId:\" + userId.toString, 0, num).map{item =>\n",
    "      val attr = item.split(\"\\\\:\")\n",
    "      (attr(0).trim.toInt, attr(1).trim.toDouble)\n",
    "    }.toArray\n",
    "  }\n",
    "}\n",
    "```\n",
    "\n",
    "## 5.3 实时推荐算法的讲解\n",
    "\n",
    "实时推荐算法的前提：\n",
    "\n",
    "1. 在Redis集群中存储了每一个用户最近对商品的K次评分。实时算法可以快速获取。\n",
    "2. 离线推荐算法已经将商品相似度矩阵提前计算到了MongoDB中。\n",
    "3. Kafka已经获取到了用户实时的评分数据。\n",
    "\n",
    "算法过程如下：\n",
    "\n",
    "实时推荐算法输入为一个评分(userId, ProductId, rate, timestamp)，而执行的核心内容包括：获取userId最近K次评分、获取productId最相似K个商品、计算候选商品的推荐优先级、更新对userId的实时推荐结果。\n",
    "\n",
    "### 5.3.1 获取用户的K次最近评分\n",
    "\n",
    "业务服务器在接收用户评分的时候，默认会将该评分情况以userId, productId, rating, timestamp的格式插入到Redis中该用户对应的队列当中，在实时算法中，只需要通过Redis客户端获取相对应的队列内容即可。\n",
    "\n",
    "```scala\n",
    "import scala.collection.JavaConversions._\n",
    "/**\n",
    "  * 获取当前最近的M次商品评分\n",
    "  * @param num  评分的个数\n",
    "  * @param userId  谁的评分\n",
    "  * @return\n",
    "  */\n",
    "def getUserRecentlyRating(num:Int, userId:Int,jedis:Jedis): Array[(Int,Double)] ={\n",
    "  //从用户的队列中取出num个评分\n",
    "  jedis.lrange(\"userId:\"+userId.toString, 0, num).map{item =>\n",
    "    val attr = item.split(\"\\\\:\")\n",
    "    (attr(0).trim.toInt, attr(1).trim.toDouble)\n",
    "  }.toArray\n",
    "}\n",
    "```\n",
    "\n",
    "### 5.3.2 获取当前商品最相似的K个商品\n",
    "\n",
    "在离线算法中，已经预先将商品的相似度矩阵进行了计算，所以每个商品productId的最相似的K个商品很容易获取：从MongoDB中读取ProductRecs数据，从productId在simHash对应的子哈希表中获取相似度前K大的那些商品。输出是数据类型为Array[Int]的数组，表示与productId最相似的商品集合，并命名为candidateProducts以作为候选商品集合。\n",
    "\n",
    "```scala\n",
    "/**\n",
    "  * 获取当前商品K个相似的商品\n",
    "  * @param num          相似商品的数量\n",
    "  * @param productId          当前商品的ID\n",
    "  * @param userId          当前的评分用户\n",
    "  * @param simProducts    商品相似度矩阵的广播变量值\n",
    "  * @param mongConfig   MongoDB的配置\n",
    "  * @return\n",
    "  */\n",
    "def getTopSimProducts(num:Int, productId:Int, userId:Int, simProducts:scala.collection.Map[Int,scala.collection.immutable.Map[Int,Double]])(implicit mongConfig: MongConfig): Array[Int] ={\n",
    "  //从广播变量的商品相似度矩阵中获取当前商品所有的相似商品\n",
    "  val allSimProducts = simProducts.get(productId).get.toArray\n",
    "  //获取用户已经评分过的商品\n",
    "  val ratingExist = ConnHelper.mongoClient(mongConfig.db)(MONGODB_RATING_COLLECTION).find(MongoDBObject(\"userId\" -> userId)).toArray.map{item =>\n",
    "    item.get(\"productId\").toString.toInt\n",
    "  }\n",
    "  //过滤掉已经评分过的商品，并排序输出\n",
    "  allSimProducts.filter(x => !ratingExist.contains(x._1)).sortWith(_._2 > _._2).take(num).map(x => x._1)\n",
    "}\n",
    "```\n",
    "\n",
    "### 5.3.3 商品推荐优先级计算\n",
    "\n",
    "对于候选商品集合simiHash和userId的最近K个评分recentRatings，算法代码内容如下：\n",
    "\n",
    "```scala\n",
    "/**\n",
    "  * 计算待选商品的推荐分数\n",
    "  * @param simProducts            商品相似度矩阵\n",
    "  * @param userRecentlyRatings  用户最近的k次评分\n",
    "  * @param topSimProducts         当前商品最相似的K个商品\n",
    "  * @return\n",
    "  */\n",
    "\n",
    "  def computeProductScores(simProducts: scala.collection.Map[Int,scala.collection.immutable.Map[Int,Double]],userRecentlyRatings:Array[(Int,Double)],topSimProducts: Array[Int]): Array[(Int,Double)] = {\n",
    "\n",
    "    //用于保存每一个待选商品和最近评分的每一个商品的权重得分\n",
    "    val score = scala.collection.mutable.ArrayBuffer[(Int,Double)]()\n",
    "\n",
    "    //用于保存每一个商品的增强因子数\n",
    "    val increMap = scala.collection.mutable.HashMap[Int,Int]()\n",
    "\n",
    "    //用于保存每一个商品的减弱因子数\n",
    "    val decreMap = scala.collection.mutable.HashMap[Int,Int]()\n",
    "\n",
    "    for (topSimProduct <- topSimProducts; userRecentlyRating <- userRecentlyRatings){\n",
    "      val simScore = getProductsSimScore(simProducts, userRecentlyRating._1, topSimProduct)\n",
    "      if(simScore > 0.6){\n",
    "        score += ((topSimProduct, simScore * userRecentlyRating._2 ))\n",
    "        if(userRecentlyRating._2 > 3){\n",
    "          increMap(topSimProduct) = increMap.getOrDefault(topSimProduct,0) + 1\n",
    "        }else{\n",
    "          decreMap(topSimProduct) = decreMap.getOrDefault(topSimProduct,0) + 1\n",
    "        }\n",
    "      }\n",
    "    }\n",
    "    score.groupBy(_._1).map{case (mid,sims) =>\n",
    "      (mid,sims.map(_._2).sum / sims.length + log(increMap.getOrDefault(mid, 1)) - log(decreMap.getOrDefault(mid, 1)))\n",
    "    }.toArray\n",
    "  }\n",
    "```\n",
    "\n",
    "其中，getProductSimScore是取候选商品和已评分商品的相似度，代码如下：\n",
    "\n",
    "```scala\n",
    "/**\n",
    "  * 获取当个商品之间的相似度\n",
    "  * @param simProducts       商品相似度矩阵\n",
    "  * @param userRatingProduct 用户已经评分的商品\n",
    "  * @param topSimProduct     候选商品\n",
    "  * @return\n",
    "  */\n",
    "def getProductsSimScore(simProducts: scala.collection.Map[Int,scala.collection.immutable.Map[Int,Double]], userRatingProduct: Int, topSimProduct: Int): Double = {\n",
    "  simProducts.get(topSimProduct) match {\n",
    "    case Some(sim) => sim.get(userRatingProduct) match {\n",
    "      case Some(score) => score\n",
    "      case None => 0.0\n",
    "    }\n",
    "    case None => 0.0\n",
    "  }\n",
    "}\n",
    "```\n",
    "\n",
    "而log是对数运算，这里实现为取2的对数（常用对数）：\n",
    "\n",
    "```scala\n",
    "  //取2的对数\n",
    "  def log(m: Int): Double = {\n",
    "    math.log(m) / math.log(2)\n",
    "  }\n",
    "```\n",
    "\n",
    "### 5.3.4 将结果保存到mongoDB\n",
    "\n",
    "saveRecsToMongoDB函数实现了结果的保存：\n",
    "\n",
    "```scala\n",
    "/**\n",
    "  * 将数据保存到MongoDB    userId -> 1,  recs -> 22:4.5|45:3.8\n",
    "  * @param streamRecs  流式的推荐结果\n",
    "  * @param mongConfig  MongoDB的配置\n",
    "  */\n",
    "  def saveRecsToMongoDB(userId: Int, streamRecs: Array[(Int,Double)])(implicit mongConfig: MongConfig): Unit = {\n",
    "    //到StreamRecs的连接\n",
    "    val streamRecsCollection = ConnHelper.mongoClient(mongConfig.db)(MONGODB_STREAM_RECS_COLLECTION)\n",
    "\n",
    "    streamRecsCollection.findAndRemove(MongoDBObject(\"userId\" -> userId))\n",
    "    //streaRecsCollection.insert(MongoDBObject(\"userId\" -> userId, \"recs\" -> streamRecs.map(x=> x._1+\":\"+x._2).mkString(\"|\")))\n",
    "    streamRecsCollection.insert(MongoDBObject(\"userId\" -> userId, \"recs\" -> streamRecs.map(x => MongoDBObject(\"productId\" -> x._1, \"score\" -> x._2))))\n",
    "\n",
    "  }\n",
    "```\n",
    "\n",
    "### 5.3.5 更新实时推荐结果\n",
    "\n",
    "当计算出候选商品的推荐优先级的数组updatedRecommends<productId, E>后，这个数组将被发送到Web后台服务器，与后台服务器上userId的上次实时推荐结果recentRecommends<productId, E>进行合并、替换并选出优先级E前K大的商品作为本次新的实时推荐。具体而言：\n",
    "\n",
    "a. 合并：将updatedRecommends与recentRecommends并集合成为一个新的<productId, E>数组；\n",
    "\n",
    "b. 替换（去重）：当updatedRecommends与recentRecommends有重复的商品productId时，recentRecommends中productId的推荐优先级由于是上次实时推荐的结果，于是将作废，被替换成代表了更新后的updatedRecommends的productId的推荐优先级；\n",
    "\n",
    "c. 选取TopK：在合并、替换后的<ProductId, E>数组上，根据每个product的推荐优先级，选择出前K大的商品，作为本次实时推荐的最终结果。\n",
    "\n",
    "## 5.4 实时系统联调\n",
    "\n",
    "我们的系统实时推荐的数据流向是：业务系统 -> 日志 -> flume 日志采集 -> kafka streaming数据清洗和预处理 -> spark streaming 流式计算。在我们完成实时推荐服务的代码后，应该与其它工具进行联调测试，确保系统正常运行。\n",
    "\n",
    "### 5.4.1 启动实时系统的基本组件\n",
    "\n",
    "启动实时推荐系统StreamingRecommender以及mongodb、redis\n",
    "\n",
    "### 5.4.2 启动zookeeper\n",
    "\n",
    "```sh\n",
    "$ bin/zkServer.sh start\n",
    "```\n",
    "\n",
    "### 5.4.3 启动kafka\n",
    "\n",
    "```sh\n",
    "bin/kafka-server-start.sh -daemon ./config/server.properties\n",
    "```\n",
    "\n",
    "### 5.4.4 构建Kafka Streaming程序\n",
    "\n",
    "在recommender下新建module，KafkaStreaming，主要用来做日志数据的预处理，过滤出需要的内容。pom.xml文件需要引入依赖：\n",
    "\n",
    "```xml\n",
    "    <dependencies>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.kafka</groupId>\n",
    "            <artifactId>kafka-streams</artifactId>\n",
    "            <version>0.10.2.1</version>\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.kafka</groupId>\n",
    "            <artifactId>kafka-clients</artifactId>\n",
    "            <version>0.10.2.1</version>\n",
    "        </dependency>\n",
    "    </dependencies>\n",
    "\n",
    "    <build>\n",
    "        <finalName>kafkastream</finalName>\n",
    "        <plugins>\n",
    "            <plugin>\n",
    "                <groupId>org.apache.maven.plugins</groupId>\n",
    "                <artifactId>maven-assembly-plugin</artifactId>\n",
    "                <configuration>\n",
    "                    <archive>\n",
    "                        <manifest>\n",
    "                            <mainClass>com.atguigu.kafkastream.Application</mainClass>\n",
    "                        </manifest>\n",
    "                    </archive>\n",
    "                    <descriptorRefs>\n",
    "                        <descriptorRef>jar-with-dependencies</descriptorRef>\n",
    "                    </descriptorRefs>\n",
    "                </configuration>\n",
    "                <executions>\n",
    "                    <execution>\n",
    "                        <id>make-assembly</id>\n",
    "                        <phase>package</phase>\n",
    "                        <goals>\n",
    "                            <goal>single</goal>\n",
    "                        </goals>\n",
    "                    </execution>\n",
    "                </executions>\n",
    "            </plugin>\n",
    "        </plugins>\n",
    "    </build>\n",
    "```\n",
    "\n",
    "在src/main/java下新建java类com.atguigu.kafkastreaming.Application\n",
    "\n",
    "```java\n",
    "package com.atguigu.kafkastream;\n",
    "\n",
    "import org.apache.kafka.streams.KafkaStreams;\n",
    "import org.apache.kafka.streams.StreamsConfig;\n",
    "import org.apache.kafka.streams.processor.TopologyBuilder;\n",
    "\n",
    "import java.util.Properties;\n",
    "\n",
    "public class Application {\n",
    "    public static void main(String[] args){\n",
    "        String brokers = \"localhost:9092\";\n",
    "        String zookeepers = \"localhost:2181\";\n",
    "        String from = \"log\";\n",
    "        String to = \"recommender\";\n",
    "\n",
    "        Properties settings = new Properties();\n",
    "        settings.put(StreamsConfig.APPLICATION_ID_CONFIG, \"logFilter\");\n",
    "        settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);\n",
    "        settings.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, zookeepers);\n",
    "\n",
    "        StreamsConfig config = new StreamsConfig(settings);\n",
    "\n",
    "        TopologyBuilder builder = new TopologyBuilder();\n",
    "\n",
    "        builder.addSource(\"SOURCE\", from)\n",
    "                .addProcessor(\"PROCESS\", () -> new LogProcessor(), \"SOURCE\")\n",
    "                .addSink(\"SINK\", to, \"PROCESS\");\n",
    "\n",
    "        KafkaStreams streams = new KafkaStreams(builder, config);\n",
    "        streams.start();\n",
    "    }\n",
    "}\n",
    "```\n",
    "\n",
    "这个程序会将topic为“log”的信息流获取来做处理，并以“recommender”为新的topic转发出去。\n",
    "\n",
    "流处理程序LogProcess.java\n",
    "\n",
    "```java\n",
    "package com.atguigu.kafkastream;\n",
    "\n",
    "import org.apache.kafka.streams.processor.Processor;\n",
    "import org.apache.kafka.streams.processor.ProcessorContext;\n",
    "\n",
    "public class LogProcessor implements Processor<byte[],byte[]> {\n",
    "    private ProcessorContext context;\n",
    "\n",
    "    public void init(ProcessorContext context) {\n",
    "        this.context = context;\n",
    "    }\n",
    "\n",
    "    public void process(byte[] dummy, byte[] line) {\n",
    "        String input = new String(line);\n",
    "        if(input.contains(\"PRODUCT_RATING_PREFIX:\")){\n",
    "            System.out.println(\"product rating coming!!!!\");\n",
    "            input = input.split(\"PRODUCT_RATING_PREFIX:\")[1].trim();\n",
    "            context.forward(\"logProcessor\".getBytes(), input.getBytes());\n",
    "        }\n",
    "    }\n",
    "\n",
    "    public void punctuate(long timestamp) {\n",
    "    }\n",
    "\n",
    "    public void close() {\n",
    "    }\n",
    "}\n",
    "```\n",
    "\n",
    "完成代码后，启动Application。\n",
    "\n",
    "5.4.5 配置并启动flume\n",
    "\n",
    "在flume的conf目录下新建log-kafka.properties，对flume连接kafka做配置：\n",
    "\n",
    "```\n",
    "agent.sources = exectail\n",
    "agent.channels = memoryChannel\n",
    "agent.sinks = kafkasink\n",
    "\n",
    "# For each one of the sources, the type is defined\n",
    "agent.sources.exectail.type = exec\n",
    "# 下面这个路径是需要收集日志的绝对路径，改为自己的日志目录\n",
    "agent.sources.exectail.command = tail –f /mnt/d/Projects/BigData/ProductRecommender/businessServer/src/main/log/agent.log\n",
    "agent.sources.exectail.interceptors = i1\n",
    "\n",
    "agent.sources.exectail.interceptors.i1.type=regex_filter\n",
    "# 定义日志过滤前缀的正则\n",
    "agent.sources.exectail.interceptors.i1.regex=.+Product_RATING_PREFIX.+\n",
    "# The channel can be defined as follows.\n",
    "agent.sources.exectail.channels = memoryChannel\n",
    "\n",
    "# Each sink's type must be defined\n",
    "agent.sinks.kafkasink.type = org.apache.flume.sink.kafka.KafkaSink\n",
    "agent.sinks.kafkasink.kafka.topic = log\n",
    "agent.sinks.kafkasink.kafka.bootstrap.servers = localhost:9092\n",
    "agent.sinks.kafkasink.kafka.producer.acks = 1\n",
    "agent.sinks.kafkasink.kafka.flumeBatchSize = 20\n",
    "\n",
    "#Specify the channel the sink should use\n",
    "agent.sinks.kafkasink.channel = memoryChannel\n",
    "\n",
    "# Each channel's type is defined.\n",
    "agent.channels.memoryChannel.type = memory\n",
    "\n",
    "# Other config values specific to each type of channel(sink or source)\n",
    "# can be defined as well\n",
    "# In this case, it specifies the capacity of the memory channel\n",
    "agent.channels.memoryChannel.capacity = 10000\n",
    "```\n",
    "\n",
    "配置好后，启动flume：\n",
    "\n",
    "```sh\n",
    "$ ./bin/flume-ng agent -c ./conf/ -f ./conf/log-kafka.properties -n agent -Dflume.root.logger=INFO,console\n",
    "```\n",
    "\n",
    "### 5.4.6 启动业务系统后台\n",
    "\n",
    "将业务代码加入系统中。注意在src/main/resources/下的log4j.properties中，log4j.appender.file.File的值应该替换为自己的日志目录，与flume中的配置应该相同。\n",
    "\n",
    "启动业务系统后台，访问localhost:8088/index.html；点击某个商品进行评分，查看实时推荐列表是否会发生变化。\n",
    "\n",
    "# 第6章 冷启动问题处理\n",
    "\n",
    "整个推荐系统更多的是依赖于用于的偏好信息进行商品的推荐，那么就会存在一个问题，对于新注册的用户是没有任何偏好信息记录的，那这个时候推荐就会出现问题，导致没有任何推荐的商品出现。\n",
    "\n",
    "我们在电商推荐中解决冷启动的方案是：给新注册的用户推荐热门的商品，例如近期热门商品、历史热门商品等策略。\n",
    "\n",
    "实际生产环境中可以根据不同的业务场景调整策略。例如资讯类应用可以先给用户一个交互式的标签页面，让用户自己选择感兴趣的标签，然后推荐用户感兴趣标签的热门内容。\n",
    "\n",
    "# 第7章 基于内容的推荐服务\n",
    "\n",
    "## 7.1 基于内容的推荐服务\n",
    "\n",
    "原始数据中的tags字段，是用户给商品打上的标签，这部分内容想要直接转成评分并不容易，不过我们可以将标签内容进行提取，得到商品的内容特征向量，进而可以通过求取相似度矩阵。这部分可以与实时推荐系统直接对接，计算出与用户当前评分商品的相似商品，实现基于内容的实时推荐。为了避免热门标签对特征提取的影响，我们还可以通过TF-IDF算法对标签的权重进行调整，从而尽可能地接近用户偏好。\n",
    "\n",
    "## 7.2 基于内容推荐的实现\n",
    "\n",
    "基于以上思想，加入TF-IDF算法的求取商品特征向量的核心代码如下：\n",
    "\n",
    "```scala\n",
    "package com.atguigu.content\n",
    "\n",
    "import org.apache.spark.SparkConf\n",
    "import org.apache.spark.sql.SparkSession\n",
    "import org.apache.spark.ml.feature.{HashingTF, IDF, Tokenizer}\n",
    "import org.apache.spark.ml.linalg.SparseVector\n",
    "import org.jblas.DoubleMatrix\n",
    "\n",
    "case class MongoConfig(uri: String, db: String)\n",
    "\n",
    "case class Product(productId: Int, name: String, categories: String, imageUrl: String, tags: String)\n",
    "//推荐\n",
    "case class Recommendation(rid: Int, r: Double)\n",
    "\n",
    "// 用户的推荐\n",
    "case class UserRecs(userId: Int, recs: Seq[Recommendation])\n",
    "\n",
    "//商品的相似度\n",
    "case class ProductRecs(productId: Int, recs: Seq[Recommendation])\n",
    "\n",
    "object ContentBasedRecommender {\n",
    "  val MONGODB_PRODUCT_COLLECTION = \"Products\"\n",
    "  val PRODUCT_RECS = \"ContentBasedProductRecs\"\n",
    "\n",
    "  def consinSim(product1: DoubleMatrix, product2: DoubleMatrix) : Double ={\n",
    "    product1.dot(product2) / ( product1.norm2() * product2.norm2() )\n",
    "  }\n",
    "\n",
    "\n",
    "  def main(args: Array[String]): Unit = {\n",
    "\n",
    "    val config = Map(\n",
    "      \"spark.cores\" -> \"local[*]\",\n",
    "      \"mongo.uri\" -> \"mongodb://localhost:27017/recommender\",\n",
    "      \"mongo.db\" -> \"reommender\"\n",
    "    )\n",
    "\n",
    "    //创建一个SparkConf配置\n",
    "    val sparkConf = new SparkConf().setAppName(\"ContentBasedRecommender\").setMaster(config(\"spark.cores\")).set(\"spark.executor.memory\",\"6G\").set(\"spark.driver.memory\",\"2G\")\n",
    "\n",
    "    //基于SparkConf创建一个SparkSession\n",
    "    val spark = SparkSession.builder().config(sparkConf).getOrCreate()\n",
    "\n",
    "    spark.sparkContext.setLogLevel(\"ERROR\")\n",
    "\n",
    "    //创建一个MongoDBConfig\n",
    "    val mongoConfig = MongoConfig(config(\"mongo.uri\"),config(\"mongo.db\"))\n",
    "\n",
    "    import spark.implicits._\n",
    "\n",
    "    val productRDD = spark\n",
    "      .read\n",
    "      .option(\"uri\",mongoConfig.uri)\n",
    "      .option(\"collection\",MONGODB_PRODUCT_COLLECTION)\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .load()\n",
    "      .as[Product]\n",
    "      .rdd\n",
    "      .map(x => (x.productId, x.name, x.tags.map(c => if(c == '|') ' ' else c)))\n",
    "\n",
    "    val productSeq = productRDD.collect()\n",
    "\n",
    "    val tagsData = spark.createDataFrame(productSeq).toDF(\"productId\", \"name\", \"tags\")\n",
    "\n",
    "    // 实例化一个分词器，默认按空格分\n",
    "    val tokenizer = new Tokenizer().setInputCol(\"tags\").setOutputCol(\"words\")\n",
    "\n",
    "    // 用分词器做转换，生成列“words”，返回一个dataframe，增加一列words\n",
    "    val wordsData = tokenizer.transform(tagsData)\n",
    "\n",
    "    wordsData.show(5)\n",
    "\n",
    "    // HashingTF是一个工具，可以把一个词语序列，转换成词频(初始特征)\n",
    "    val hashingTF = new HashingTF().setInputCol(\"words\").setOutputCol(\"rawFeatures\").setNumFeatures(189)\n",
    "\n",
    "    // 用 HashingTF 做处理，返回dataframe\n",
    "    val featurizedData = hashingTF.transform(wordsData)\n",
    "\n",
    "    // IDF 也是一个工具，用于计算文档的IDF\n",
    "    val idf = new IDF().setInputCol(\"rawFeatures\").setOutputCol(\"features\")\n",
    "\n",
    "    // 将词频数据传入，得到idf模型（统计文档）\n",
    "    val idfModel = idf.fit(featurizedData)\n",
    "\n",
    "    // 模型对原始数据做处理，计算出idf后，用tf-idf得到新的特征矩阵\n",
    "    val rescaledData = idfModel.transform(featurizedData)\n",
    "\n",
    "    rescaledData.show(5)\n",
    "\n",
    "    val productFeatures = rescaledData.map{\n",
    "      case row => {\n",
    "        if (row.getAs[Int](\"productId\") == 160597 || row.getAs[Int](\"productId\") == 8195) {\n",
    "          println(row)\n",
    "        }\n",
    "        (row.getAs[Int](\"productId\"), row.getAs[SparseVector](\"features\").toArray)\n",
    "      }\n",
    "    }\n",
    "    .rdd\n",
    "    .map(x => {\n",
    "      (x._1, new DoubleMatrix(x._2) )\n",
    "    })\n",
    "\n",
    "    val productRecs = productFeatures.cartesian(productFeatures)\n",
    "      .filter{case (a, b) => a._1 != b._1}\n",
    "      .map {\n",
    "        case (a, b) => {\n",
    "          if (a._1==160597 && b._1==8195) {\n",
    "            println(a._1, a._2, b._1, b._2)\n",
    "          }\n",
    "          val simScore = this.consinSim(a._2, b._2)\n",
    "          (a._1, (b._1, simScore))\n",
    "        }\n",
    "      }\n",
    "      .groupByKey()\n",
    "      .map {\n",
    "        case (productId, items) => ProductRecs(productId, items.toList.sortWith(_._2 > _._2).map(x => Recommendation(x._1, x._2)).take(5))\n",
    "      }\n",
    "      .toDF()\n",
    "\n",
    "    productRecs.show(5)\n",
    "\n",
    "    productRecs\n",
    "      .write\n",
    "      .option(\"uri\", mongoConfig.uri)\n",
    "      .option(\"collection\", PRODUCT_RECS)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "\n",
    "    //关闭Spark\n",
    "    spark.close()\n",
    "  }\n",
    "}\n",
    "```\n",
    "\n",
    "然后通过商品特征向量进而求出相似度矩阵，就可以为实时推荐提供基础，得到用户推荐列表了。可以看出，基于内容和基于隐语义模型，目的都是为了提取出物品的特征向量，从而可以计算出相似度矩阵。而我们的实时推荐系统算法正是基于相似度来定义的。\n",
    "\n",
    "当然，别忘记在`pom.xml`中添加依赖：\n",
    "\n",
    "```xml\n",
    "    <dependencies>\n",
    "\n",
    "        <!-- 引入Spark相关的Jar包 -->\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-core_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-sql_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-streaming_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-mllib_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-graphx_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "\n",
    "        <!-- 加入MongoDB的驱动 -->\n",
    "        <!-- 用于代码方式连接MongoDB -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb</groupId>\n",
    "            <artifactId>casbah-core_2.11</artifactId>\n",
    "            <version>${casbah.version}</version>\n",
    "        </dependency>\n",
    "        <!-- 用于Spark和MongoDB的对接 -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb.spark</groupId>\n",
    "            <artifactId>mongo-spark-connector_2.11</artifactId>\n",
    "            <version>${mongodb-spark.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <!-- 引入Scala -->\n",
    "        <dependency>\n",
    "            <groupId>org.scala-lang</groupId>\n",
    "            <artifactId>scala-library</artifactId>\n",
    "            <version>${scala.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <dependency>\n",
    "            <groupId>org.scalanlp</groupId>\n",
    "            <artifactId>jblas</artifactId>\n",
    "            <version>${jblas.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "    </dependencies>\n",
    "```\n",
    "\n",
    "# 第8章 基于物品的协同过滤\n",
    "\n",
    "基于同现相似度的计算公式来计算不同物品间的相似度。\n",
    "\n",
    "$$\n",
    "w_{ij} = \\frac {\\vert N_i \\cap N_j \\vert} {\\sqrt {\\vert N_i \\vert \\vert N_j \\vert}}\n",
    "$$\n",
    "\n",
    "其中$N_i$为购买商品$i$的用户列表，$N_j$为购买商品$j$的用户列表。\n",
    "\n",
    "核心代码如下：\n",
    "\n",
    "```scala\n",
    "package com.atguigu.itemcf\n",
    "\n",
    "import org.apache.spark.SparkConf\n",
    "import org.apache.spark.sql.SparkSession\n",
    "\n",
    "//  物品信息\n",
    "case class Product(productId: Int, name: String, categories: String, imageUrl: String, tags: String)\n",
    "\n",
    "case class MongoConfig(uri:String, db:String)\n",
    "\n",
    "//  用户-物品-评分\n",
    "case class Rating(userId: Int, productId: Int, score: Double, timestamp: Int)\n",
    "\n",
    "//  用户信息\n",
    "case class User(userId: Int)\n",
    "\n",
    "case class Recommendation(rid: Int, r: Double)\n",
    "\n",
    "case class ProductRecs(productId: Int, recs:Seq[Recommendation])\n",
    "\n",
    "object ItemCFRecommender {\n",
    "  // 同现相似度计算公式\n",
    "  // 比如：对A评分的人数100，对B评分的人数100，交集人数20\n",
    "  // 同现相似度：20 / 100 = 0.2\n",
    "  def cooccurrence(numOfRatersForAAndB: Long, numOfRatersForA: Long, numOfRatersForB: Long): Double = {\n",
    "    numOfRatersForAAndB / math.sqrt(numOfRatersForA * numOfRatersForB)\n",
    "  }\n",
    "\n",
    "  val MONGODB_PRODUCT_COLLECTION = \"Products\"\n",
    "  val MONGODB_RATING_COLLECTION = \"Rating\"\n",
    "  val PRODUCT_RECS = \"ItemCFProductRecs\"\n",
    "\n",
    "\n",
    "  def main(args: Array[String]): Unit = {\n",
    "    val config = Map(\n",
    "      \"spark.cores\" -> \"local[*]\",\n",
    "      \"mongo.uri\" -> \"mongodb://localhost:27017/recommender\",\n",
    "      \"mongo.db\" -> \"reommender\"\n",
    "    )\n",
    "\n",
    "    //创建一个SparkConf配置\n",
    "    val sparkConf = new SparkConf().setAppName(\"ItemCFRecommender\").setMaster(config(\"spark.cores\")).set(\"spark.executor.memory\",\"6G\").set(\"spark.driver.memory\",\"2G\")\n",
    "\n",
    "    //基于SparkConf创建一个SparkSession\n",
    "    val spark = SparkSession.builder().config(sparkConf).getOrCreate()\n",
    "\n",
    "    spark.sparkContext.setLogLevel(\"ERROR\")\n",
    "\n",
    "    //创建一个MongoDBConfig\n",
    "    val mongoConfig = MongoConfig(config(\"mongo.uri\"),config(\"mongo.db\"))\n",
    "\n",
    "    import spark.implicits._\n",
    "\n",
    "    // 读取mongoDB中的业务数据\n",
    "    val ratingDF = spark\n",
    "      .read\n",
    "      .option(\"uri\", mongoConfig.uri)\n",
    "      .option(\"collection\", MONGODB_RATING_COLLECTION)\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .load()\n",
    "      .as[Rating]\n",
    "      .rdd\n",
    "      .map {\n",
    "        rating => {\n",
    "          (rating.userId, rating.productId, rating.score)\n",
    "        }\n",
    "      }\n",
    "      .cache()\n",
    "      .toDF(\"userId\", \"productId\", \"rating\")\n",
    "\n",
    "    val numRatersPerProduct = ratingDF.groupBy(\"productId\").count().alias(\"nor\")\n",
    "\n",
    "    // 在原记录基础上加上product的打分者的数量\n",
    "    val ratingsWithSize = ratingDF.join(numRatersPerProduct, \"productId\")\n",
    "\n",
    "    // 执行内联操作\n",
    "    val joinedDF = ratingsWithSize.join(ratingsWithSize, \"userId\")\n",
    "      .toDF(\"userId\", \"product1\", \"rating1\", \"nor1\", \"product2\", \"rating2\", \"nor2\")\n",
    "\n",
    "    joinedDF\n",
    "      .selectExpr(\"userId\", \"product1\", \"nor1\", \"product2\", \"nor2\")\n",
    "      .createOrReplaceTempView(\"joined\")\n",
    "\n",
    "    //  计算必要的中间数据，注意此处有WHERE限定，只计算了一半的数据量\n",
    "    val sparseMatrix = spark.sql(\n",
    "      \"\"\"\n",
    "        |SELECT product1\n",
    "        |, product2\n",
    "        |, count(userId) as size\n",
    "        |, first(nor1) as nor1\n",
    "        |, first(nor2) as nor2\n",
    "        |FROM joined\n",
    "        |GROUP BY product1, product2\n",
    "      \"\"\".stripMargin)\n",
    "      .cache()\n",
    "\n",
    "    //  计算物品相似度\n",
    "    var sim = sparseMatrix.map(row => {\n",
    "      val size = row.getAs[Long](2)\n",
    "      val numRaters1 = row.getAs[Long](3)\n",
    "      val numRaters2 = row.getAs[Long](4)\n",
    "\n",
    "      val cooc = cooccurrence(size, numRaters1, numRaters2)\n",
    "      (row.getInt(0), row.getInt(1), cooc)\n",
    "    }).toDF(\"productId_01\", \"productId_02\", \"cooc\")\n",
    "\n",
    "    val simDF = sim\n",
    "      .map{\n",
    "        case row => (\n",
    "          row.getAs[Int](\"productId_01\"),\n",
    "          row.getAs[Int](\"productId_02\"),\n",
    "          row.getAs[Double](\"cooc\")\n",
    "        )\n",
    "      }\n",
    "      .rdd\n",
    "      .map(\n",
    "        x => (x._1, (x._2, x._3))\n",
    "      )\n",
    "      .groupByKey()\n",
    "      .map {\n",
    "        case (productId, items) => ProductRecs(productId, items.toList.filter(x => x._1 != productId).sortWith(_._2 > _._2).map(x => Recommendation(x._1,x._2)).take(5))\n",
    "      }\n",
    "      .toDF()\n",
    "\n",
    "    simDF\n",
    "      .write\n",
    "      .option(\"uri\", mongoConfig.uri)\n",
    "      .option(\"collection\", PRODUCT_RECS)\n",
    "      .mode(\"overwrite\")\n",
    "      .format(\"com.mongodb.spark.sql\")\n",
    "      .save()\n",
    "\n",
    "    //关闭Spark\n",
    "    spark.close()\n",
    "\n",
    "  }\n",
    "\n",
    "}\n",
    "```\n",
    "\n",
    "别忘了添加依赖：\n",
    "\n",
    "```xml\n",
    "    <dependencies>\n",
    "\n",
    "        <!-- 引入Spark相关的Jar包 -->\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-core_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-sql_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-streaming_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-mllib_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "        <dependency>\n",
    "            <groupId>org.apache.spark</groupId>\n",
    "            <artifactId>spark-graphx_2.11</artifactId>\n",
    "            <version>2.1.1</version>\n",
    "            <!-- provider如果存在，那么运行时该Jar包不存在，也不会打包到最终的发布版本中，只是编译器有效 -->\n",
    "            <!--<scope>provided</scope>-->\n",
    "        </dependency>\n",
    "\n",
    "        <!-- 加入MongoDB的驱动 -->\n",
    "        <!-- 用于代码方式连接MongoDB -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb</groupId>\n",
    "            <artifactId>casbah-core_2.11</artifactId>\n",
    "            <version>${casbah.version}</version>\n",
    "        </dependency>\n",
    "        <!-- 用于Spark和MongoDB的对接 -->\n",
    "        <dependency>\n",
    "            <groupId>org.mongodb.spark</groupId>\n",
    "            <artifactId>mongo-spark-connector_2.11</artifactId>\n",
    "            <version>${mongodb-spark.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <!-- 引入Scala -->\n",
    "        <dependency>\n",
    "            <groupId>org.scala-lang</groupId>\n",
    "            <artifactId>scala-library</artifactId>\n",
    "            <version>${scala.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "        <dependency>\n",
    "            <groupId>org.scalanlp</groupId>\n",
    "            <artifactId>jblas</artifactId>\n",
    "            <version>${jblas.version}</version>\n",
    "        </dependency>\n",
    "\n",
    "    </dependencies>\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
